My C# project is taking xml and extracting pertinent data, one of which pieces is a date time value. The following code works correctly on my desktop running Win8.1 and .NET4. However when I run it through mono, it's failing to parse the data.
using glob = System.Globalization;
DateTimeOffset dt = DateTimeOffset.MinDate;
string[] fmts = new string[]
{
"MMM dd, yyyy hh:mm tt EDT",
"MMM dd, yyyy hh:mm tt EST",
"MMM dd, yyyy hh:mm tt CDT",
"MMM dd, yyyy hh:mm tt CST",
"MMM dd, yyyy hh:mm tt MDT",
"MMM dd, yyyy hh:mm tt MST",
"MMM dd, yyyy hh:mm tt AKST",
"MMM dd, yyyy hh:mm tt AKDT",
"MMM dd, yyyy hh:mm tt HST",
"MMM dd, yyyy hh:mm tt PST",
"MMM dd, yyyy hh:mm tt PDT"
};
var dtString = z.Substring(pos1 + 5, pos2 - pos1 - 1 - 5).Replace("ft", "").Trim();
dtString = dtString.Substring(0, 1).ToUpper() + dtString.Substring(1);
dtString = dtString.Substring(0, dtString.Length - 7)
+ dtString.Substring(dtString.Length - 7).ToUpper();
DateTimeOffset.TryParseExact(dtString, fmts,
glob.CultureInfo.InvariantCulture, glob.DateTimeStyles.None, out dt);
To check if the conversion worked ok, I do this:
if (dt == DateTimeOffset.MinDate)
Console.WriteLine("failed to convert dt = MinValue -> " + dtString);
Here's an example of the data string being processed:
raw: mar 21, 2015 10:30 am cdt
after my formatting: Mar 21, 2015 10:15 AM CDT
It's not specific to the CDT tz - I get the same issue for all timezones.
When I run $ date on the Linux box, it's reporting the same date, time and tz as my desktop, in this format (Mon Mar 23 11:31:16 EDT 2015).
The section is wrapped in a try/catch, but no exceptions are being thrown (also have Console output in there).
I can code around it by changing the string around before TryParse, but it would seem this method was designed so that this is not necessary.
Is this a bug (or am I missing something)? If so where does one report them?
Thanks
A few points:
In the code you posted, the part where you manipulate the dtString variable is meaningless to us, because you didn't include values for pos1 or pos2. It seems quite messy, and in general - that sort of manipulation should be avoided if possible. I'm not sure what it has to do with your question, if anything.
You are using the TryParseExact method, which returns a boolean true on success - so the comparison check is unnecessary. (Also, the field is called MinValue, not MinDate)
Time zone abbreviations are not valid in format strings. The letters in the string could be confused with actual custom formatting values. If you wanted to exclude them, you would place them in single-tick or double-tick quotation marks.
In general, time zone abbreviations should not be used for input. There are just too many ambiguities. For example, this list of abbreviations shows 5 possible interpretations of "CST".
The parsers that come with the DateTime and DateTimeOffset types do not understand time zone abbreviations at all. You claim it works fine on your desktop under .NET 4, but I call BS.
As you can see, it did not interpret the offset as CDT (-05:00). Instead it took the local time zone from my computer, which happens to be PDT (-07:00).
The correct way to deal with this is to parse the date input as a DateTime, then use some other mechanism to determine the offset. If you MUST use the time zone abbreviation, and you are absolutely sure you only have the time zones you showed above, and they're all from the united states, then it would go something like this:
// define the list that you care about
private static readonly Dictionary<string, TimeSpan> Abbreviations = new Dictionary<string, TimeSpan>
{
{"EDT", TimeSpan.FromHours(-4)},
{"EST", TimeSpan.FromHours(-5)},
{"CDT", TimeSpan.FromHours(-5)},
{"CST", TimeSpan.FromHours(-6)},
{"MDT", TimeSpan.FromHours(-6)},
{"MST", TimeSpan.FromHours(-7)},
{"PDT", TimeSpan.FromHours(-7)},
{"PST", TimeSpan.FromHours(-8)},
{"AKDT", TimeSpan.FromHours(-8)},
{"AKST", TimeSpan.FromHours(-9)},
{"HST", TimeSpan.FromHours(-10)}
};
static DateTimeOffset ParseInput(string input)
{
// get just the datetime part, without the abbreviation
string dateTimePart = input.Substring(0, input.LastIndexOf(" ", StringComparison.Ordinal));
// parse it to a datetime
DateTime dt;
bool success = DateTime.TryParseExact(dateTimePart, "MMM dd, yyyy hh:mm tt",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
// handle bad input
if (!success)
{
throw new ArgumentException("Invalid input string.", "input");
}
// get the abbreviation from the input string
string abbreviation = input.Substring(input.LastIndexOf(" ", StringComparison.Ordinal) + 1)
.ToUpperInvariant();
// look up the offset from the abbreviation
TimeSpan offset;
success = Abbreviations.TryGetValue(abbreviation, out offset);
if (!success)
{
throw new ArgumentException("Unknown time zone abbreviation.", "input");
}
// apply the offset to the datetime, and return
return new DateTimeOffset(dt, offset);
}
Now it will return the correct output:
string dtString = "Mar 21, 2015 10:15 AM CDT";
DateTimeOffset dto = ParseInput(dtString);
Console.WriteLine(dto);
Also note that if you were really trying to cover all legal US time zones, you should also consider adding HAST, HADT, CHST, SST, and AST to the list.
Related
The dates are recorded as follows in the logs:
08 груд. 2017 00:00:06,694
I've been using Linqpad to try to come up with a valid date time mask using the Ukrainian culture, and this is what I've tried:
var dateString = "08 груд. 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(
dateString,
"dd MMMM. yyyy HH:mm:ss,fff",
new CultureInfo("uk-UA"),
DateTimeStyles.None,
out date);
Console.WriteLine(date);
This does not work, and the output from this script is:
1/1/0001 12:00:00 AM
This same approach has worked well for me for several other languages, so I'm puzzled as to what is happening here. As best as I can tell, the month is not being parsed correctly. I've try substituting "hrud." for the month value (from: https://www.loc.gov/aba/pcc/conser/conserhold/Mosabbr.html), but that does not work either.
MMMM format specifier for month means "full month name". You can see what are full month names for given culture with:
var culture = new CultureInfo("uk-UA");
var monthNames = culture.DateTimeFormat.MonthNames;
For this culture, december full name is "грудень", not "груд". You might think to use "short month name" format specifier MMM. You can look "short names" for month for given culture like this:
var culture = new CultureInfo("uk-UA");
var monthNames = culture.DateTimeFormat.AbbreviatedMonthNames;
However you will see that short name for december is "гру" and still not "груд". So to parse your string with default month names for your culture you need to either do:
var dateString = "08 грудень 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(dateString, #"dd MMMM yyyy HH:mm:ss,fff", new CultureInfo("uk-UA"), DateTimeStyles.None, out date);
Or
var dateString = "08 гру. 2017 00:00:06,694";
DateTime date;
DateTime.TryParseExact(dateString, #"dd MMM. yyyy HH:mm:ss,fff", new CultureInfo("uk-UA"), DateTimeStyles.None, out date);
Another option is to adjust culture month names for your case, like this (note that it will not modify global culture settings, only month name for this particular CultureInfo instance, so there is no danger in doing this):
var dateString = "08 груд. 2017 00:00:06,694";
DateTime date;
var culture = new CultureInfo("uk-UA");
var defaultShortNames = culture.DateTimeFormat.AbbreviatedMonthNames;
var defaultShortGenitiveNames = culture.DateTimeFormat.AbbreviatedMonthGenitiveNames;
// obviously modify all month names as necessary
defaultShortNames[11] = "Груд";
defaultShortGenitiveNames[11] = "груд";
culture.DateTimeFormat.AbbreviatedMonthNames = defaultShortNames;
culture.DateTimeFormat.AbbreviatedMonthGenitiveNames = defaultShortGenitiveNames;
// store this modified culture and reuse when necessary
// that MMM format consists of 3 letters is irrelevant - it will still
// work fine with abbreviated month names of 4 characters or more
DateTime.TryParseExact(dateString, #"dd MMM. yyyy HH:mm:ss,fff", culture, DateTimeStyles.None, out date);
As others have mentioned, MMMM is the full month name and MMM is the three-character abbreviated month name, so neither will work out of the box. Rather than hard-code month names or modify the CultureInfo, I'd prefer to pre-process the string to truncate the month to the 3 characters parseable with the MMM custom format string, either with regular expressions (heavyweight) or directly:
var sb = new StringBuilder (date.Length) ;
var nc = 0 ;
foreach (var ch in date)
{
if (char.IsLetter (ch) && nc++ >= 3) continue ;
sb.Append (ch) ;
}
return DateTime.ParseExact ("dd MMM. yyyy HH:mm:ss,fff", ...) ;
In my ASP.Net app, I am receiving a date string from PayPal and when I try to convert it to UTC date it always fails. I have tried this conversion in LINQPad tool but I always get that the date string could not be successfully parsed.
The date string that my ASP.Net page receives from PayPal is like this: 08:45:29 May 25, 2016 PDT
Question: How can I successfully convert the PayPal received date to UTC date in C#? The code that I have tried so far is given below.
Code in LINQPad for conversion of PayPal date to UTC date
string payPalDateString = "08:45:29 May 25, 2016 PDT";
DateTime date = DateTime.Now;
if( DateTime.TryParse(payPalDateString, out date) == true) {
"payPalDateString was successfully parsed".Dump();
DateTime dateUTC = date.ToUniversalTime();
dateUTC.Dump("payPalDateString in UTC is as below");
} else {
payPalDateString.Dump("payPalDateString was NOT successfully parsed");
}
PayPal documentation says the following about the date it sends.
Time/Date stamp generated by PayPal, in the following format: HH:MM:SS DD Mmm YY, YYYY PST
The above date format mentioned in PayPal documentation should actually have been: HH:mm:ss MMM dd, yyyy PST
Please refer to the below logic to parse the DateTime exactly the way it was coming from Paypal
DateTime newDate;
DateTime.TryParseExact("08:45:29 May 25, 2016 PDT",
"HH:mm:ss MMM dd, yyyy PDT",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out newDate);
var utcDateTime = newDate.ToUniversalTime();
I have added dotnetfiddle code
Since OP is not sure about the incoming time zone format to be in PDT, he was suggested to dynamically substitute time zone in the conversion format. He came up with this logic.
String.Format("HH:mm:ss MMM dd, yyyy {0}",
payPalDateString.Substring(payPalDateString.Length - 3))
Please note that there could be a number of other alternative ways to substitute the time zone at run time. This solution doesn't cover any error handling like if the input string doesn't come up with any time zone!!
Is you want to be able to support, say PST and PDT in your strings, I would create some sort of mapping from the abbreviations to an offset. Time zone abbreviations are not unique so you will need to include only the ones that are relevant to your data (and hope that PayPal doesn't use non-unique offsets like CST). You could start with what you know and add more as necessary:
Dictionary<string, string> TimeZones = new Dictionary<string, string>
{
{"PST", "-08:00"},
{"PDT", "-07:00"},
// more as needed
};
string s = "08:45:29 May 25, 2016 PDT";
StringBuilder sb = new StringBuilder(s);
foreach(var kvp in TimeZones)
sb = sb.Replace(kvp.Key,kvp.Value);
s = sb.ToString();
DateTime dt;
bool success = DateTime.TryParseExact(s,
"HH:mm:ss MMM dd, yyyy zzz",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
I have two string variables. The first one is from a label (This date will be subject to changed dependant on a datetimepicker). The second one is a time that is selected in a combo box. The format is in this example -
lblActualDate.Text - 11 June 2015
comboStartTime.Text - 12.00AM
I am getting errors about the strings not being in the correct format to convert to date time.
My aim is to make an instance with the values from a form
Here is my code -
private void btnSave_Click(object sender, EventArgs e)
{
string dateString = lblActualDate.Text + " " + comboStartTime.SelectedItem;
DateTime startTime = DateTime.ParseExact(dateString, "dd MMMM yyyy hh.mmtt", CultureInfo.InvariantCulture);
int length = int.Parse(comboLength.SelectedText);
string description = txtBoxSubject.Text;
string location = txtBoxLocation.Text;
Appointment newAppointment = new Appointment(startTime, length, description, location);
Appointments appointments = new Appointments();
appointments.Add(newAppointment);
appointments.Save();
txtBoxLocation.Clear();
txtBoxSubject.Clear();
Dispose();
}
Convert.ToDateTime uses standard date and time formats of your CurrentCulture. That means your string format doesn't match one of these formats.
You can use custom date and time formats to parse your string like;
string s = "11 June 201512.00AM";
DateTime startTime = DateTime.ParseExact(s, "dd MMMM yyyyhh.mmtt",
CultureInfo.InvariantCulture);
Also consider to put a white space between your date and time part.
Most likely you've got some combinations with one digit, and others with two digits in either the day or hour portions of your date/time.
You can allow all the possibilities by building up an array of allowable formats and passing that to ParseExact:
string[] formats = { "d MMMM yyyy h.mmtt", "d MMMM yyyy hh.mmtt", "dd MMMM yyyy h.mmtt", "dd MMMM yyyy hh.mmtt" };
DateTime startTime = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
i got date in my db in the form of MMM DD,YYYY
String thisDate1 = "Jan 05, 2009";
in order to get arithmetic operations such as add days i have to change it to standard format i.e mm/dd/yy. how can i do this. please help
Your string is fine as-is, you can use DateTime.Parse to convert it to a DateTime object which you can do your arithmetic on, like so:
var thisDate = DateTime.Parse(thisDate1);
var nextDate = thisDate.AddDays(1);
var nextDateAsString = nextDate.ToString("MMM dd, yyyy");
Also be careful with your casing, your current string is actually in MMM dd, yyyy format. DD would actually give you the letters DD themselves, as would YYYY. mm is minutes, while MM is for months. You can find more details on this on MSDN.
Also, as #HansPassant pointed out, you don't want to be storing your dates in a string until the last possible moment.
I would like to log a payment_date in this format in a SQL Server database.
Update. Instinct was right on this one. Found a solution here: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html, verifying... of course, if Paypal ever moves out of the West Coast, I'll be in trouble. Is there a better way to parse this? Maybe with TimeZone?
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// convert to local timezone
outputDateTime = outputDateTime.AddHours(3);
return outputDateTime;
}
Wait a sec, that code above is completely wrong for me. I'm on the West Coast! Ideally this should be updated to send the date to a proper UTC DateTime and handle any time zone. Also the code above doesn't handle PDT properly (if converted to UTC).
Update2. Apparently, at least in previous versions, the sandbox would return "Feb." while the live returns "Feb". Lol. Someone save me!
Update3. Link to Regex version http://www.ifinity.com.au/Blog/EntryId/77/Converting-PayPal-Dates-to-Net-DateTime-using-Regex, but debugging could be an issue. Regex does not seem like the right way to do this. There must be a better way.
/// <summary>
/// Converts a PayPal datestring into a valid .net datetime value
/// </summary>
/// <param name="dateValue">a string containing a PayPal date</param>
/// <param name="localUtcOffset">the number of hours from UTC/GMT the local
/// time is (ie, the timezone where the computer is)</param>
/// <returns>Valid DateTime value if successful, DateTime.MinDate if not</returns>
private static DateTime ConvertFromPayPalDate(string rawPayPalDate, int localUtcOffset)
{
/* regex pattern splits paypal date into
* time : hh:mm:ss
* date : Mmm dd yyyy
* timezone : PST/PDT
*/
const string payPalDateRegex = #"(?<time>\d{1,2}:\d{2}:\d{2})\s(?<date>(?<
Mmm>[A-Za-z\.]{3,5})\s(?<dd>\d{1,2}),?\s(?<yyyy>\d{4}))\s(?<tz>[A-Z]{0,3})";
//!important : above line broken over two lines for formatting - rejoin in code editor
//example 05:49:56 Oct. 18, 2009 PDT
// 20:48:22 Dec 25, 2009 PST
Match dateMatch = Regex.Match(rawPayPalDate, payPalDateRegex, RegexOptions.IgnoreCase);
DateTime time, date = DateTime.MinValue;
//check to see if the regex pattern matched the supplied string
if (dateMatch.Success)
{
//extract the relevant parts of the date from regex match groups
string rawDate = dateMatch.Groups["date"].Value;
string rawTime = dateMatch.Groups["time"].Value;
string tz = dateMatch.Groups["tz"].Value;
//create date and time values
if (DateTime.TryParse(rawTime, out time) && DateTime.TryParse(rawDate, out date))
{
//add the time to the date value to get the datetime value
date = date.Add(new TimeSpan(time.Hour, time.Minute, time.Second));
//adjust for the pdt timezone. Pass 0 to localUtcOffset to get UTC/GMT
int offset = localUtcOffset + 7; //pdt = utc-7, pst = utc-8
if (tz == "PDT")//pacific daylight time
date = date.AddHours(offset);
else //pacific standard time
date = date.AddHours(offset + 1);
}
}
return date;
}
I haven't done any C# since 2006, so this code probably doesn't compile. Test it before you fly!
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// Get the offset.
// If C# supports switching on strings, it's probably more sensible to do that.
int offset;
if (payPalDateTime.EndsWith(" PDT"))
{
offset = 7;
}
else if (payPalDateTime.EndsWith(" PST"))
{
offset = 8;
}
else
{
throw some exception;
}
// We've "parsed" the time zone, so remove it from the string.
payPalDatetime = payPalDateTime.Substring(0,payPalDateTime.Length-4);
// Same formats as above, but with PST/PDT removed.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy", "HH:mm:ss MMM. dd, yyyy" };
// Parse the date. Throw an exception if it fails.
DateTime ret = DateTime.ParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// Add the offset, and make it a universal time.
return ret.AddHours(offset).SpecifyKind(DateTimeKind.Universal);
}
This should work
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
CultureInfo enUS = new CultureInfo("en-US");
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT",
"HH:mm:ss dd MMM yyyy PST", "HH:mm:ss dd MMM. yyyy PST", "HH:mm:ss dd MMM yyyy PDT", "HH:mm:ss dd MMM. yyyy PDT"};
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out outputDateTime);
// convert to local timezone
TimeZoneInfo hwZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
outputDateTime = TimeZoneInfo.ConvertTime(outputDateTime, hwZone, TimeZoneInfo.Local);
return outputDateTime;
}
The code in this post seems to work fine: http://www.codeillustrator.com/2010/03/converting-paypal-paymentdate-to-net.html
using System;
using System.Globalization;
public static class PayPalTransaction
{
public static DateTime ConvertPayPalDateTime(string payPalDateTime)
{
// accept a few different date formats because of PST/PDT timezone and slight month difference in sandbox vs. prod.
string[] dateFormats = { "HH:mm:ss MMM dd, yyyy PST", "HH:mm:ss MMM. dd, yyyy PST", "HH:mm:ss MMM dd, yyyy PDT", "HH:mm:ss MMM. dd, yyyy PDT" };
DateTime outputDateTime;
DateTime.TryParseExact(payPalDateTime, dateFormats, new CultureInfo("en-US"), DateTimeStyles.None, out outputDateTime);
// convert to local timezone
outputDateTime = outputDateTime.AddHours(3);
return outputDateTime;
}
}
(answer cross-posted for this similar question: How to cast this date and save to database)
Assuming you have already parsed the date with DateTime.ParseExact() (or one of the other similar methods) you can call DateTime.ToUniversalTime()
EDIT: perhaps TimeZoneInfo.ConvertTimeToUtc is more appropriate:
The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.