My app has a DateTime picker control that send selected date in this format: "Wed Mar 01 2017", In server side I'm doing Convert.ToDateTime("Wed Mar 01 2017").
With everything date until today this work fine, but with "Wed Mar 01 2017" its throw Invalid format exception.
Why is that?
You need to use ParseExact or TryParseExact and specify the format like:
DateTime dt;
if(DateTime.TryParseExact("Wed Mar 01 2017","ddd MMM dd yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//invalid date
}
The reason it is failing on your machine is due to a culture that doesn't support the format, otherwise your code should work for en-US culture.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
DateTime dt = Convert.ToDateTime("Wed Mar 01 2017");
Just make sure that the culture is not changed on your machine.
To be on the safe side, it is always a better idea to parse the date using the format with InvariantCulture so that you can support your applications across multiple cultures.
check DateTime.ParseExact
DateTime.ParseExcact("Wed Mar 01 2017","ddd MMM dd yyyy",CultureInfo.InvariantCulture);
Try this code
var date = "Wed Mar 01 2017";
Console.WriteLine(DateTime.ParseExact(date, "ddd MMM dd yyyy", CultureInfo.InvariantCulture));
Related
I have date object in JavaScript which give me: "Wed Oct 01 2014 00:00:00 GMT+0200";
I try to parse it but I get an exception:
string Date = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTiem d = DateTime.ParseExact(Date,
"ddd MM dd yyyy HH:mm:ss GMTzzzzz",
CultureInfo.InvariantCulture);
MM format specifier is 2 digit month number from 01 to 12.
You need to use MMM format specifier instead for abbreviated name of month.
And for your +0200 part, you need to use K format specifier which has time zone information instead of zzzzz.
And you need to use single quotes for your GMT part as 'GMT' to specify it as literal string delimiter.
string s = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Any z format specifier is not recommended with DateTime parsing. Because they represents signed offset of local time zone UTC value and this specifier doesn't effect DateTime.Kind property. And DateTime doesn't keep any offset value.
That's why this specifier fits with DateTimeOffset parsing instead.
How can I convert this string:
string aa ="Thu Jul 02 2015 00:00:00 GMT+0100 (GMT Standard Time)";
into a DateTime.
I tried to use the Convert.ToDateTime(aa); but didn't work
Thanks.
EDIT: error message - The string was not recognized as a valid DateTime
You can use DateTime.TryParseExact with the correct format string:
string dtString = "Thu Jul 02 2015 00:00:00 GMT+0100";
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K";
DateTime date;
bool validFormat = DateTime.TryParseExact(dtString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Console.Write(validFormat ? date.ToString() : "Not a valid format");
If the string contains (GMT Standard Time) at the end you could simply remove it first:
dtString = dtString.Replace("(GMT Standard Time)", "").Trim();
or use this format pattern:
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'";
Further informations: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Using DateTime.Parse Method:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Since you have an UTC offset in your string, I would prefer to parse DateTimeOffset instead of DateTime. And there is no way to parse your GMT and (GMT Standard Time) parts without escape them.
Both DateTime and DateTimeOffset are timezone awareness by the way. DateTimeOffset little bit better than DateTime for this situation. It has UTC Offset but this doesn't guaranteed the timezone information because different timezones can have same offset value.
Even if they are, time zone abbreviations are not standardized. CST has several meanings for example.
string s = "Thu Jul 02 2015 00:00:00 GMT+01:00 (GMT Standard Time)";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as {02.07.2015 00:00:00 +01:00}
I have a situation in which I am receiving date as a string in following format.
"Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)"
I need to convert it to following format in c# (Either date/string) for further processing
YYYY-MM-DD (2014-01-13)
Convert.ToDateTime(SelectedData)
Above code thorws following error:
'Convert.ToDateTime(SelectedData)' threw an exception
of type 'System.FormatException' System.DateTime {System.FormatException}
Any suggestions?
I can't change the format in which I am receiving the date
Best Regards.
You're going to need to use DateTime.ParseExact:
var date = DateTime.ParseExact(
"Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)",
"ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture);
after parsing the date you can then send it out your way:
date.ToString("yyyy-MM-dd");
Here's an Ideone to prove it.
Convert.ToDateTime uses standart date and time formats and this is not a standart DateTime format.
If your GMT+0000 (GMT Standard Time) is defult in your string, you can use DateTime.ParseExact instead like;
string s = "Mon Jan 13 2014 00:00:00 GMT+0000 (GMT Standard Time)";
var date = DateTime.ParseExact(s,
"ddd MMM dd yyyy HH:mm:ss 'GMT+0000 (GMT Standard Time)'",
CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("yyyy-MM-dd"));
Output will be;
2014-01-13
Here a demonstration.
For more information, take a loo at:
Custom Date and Time Format Strings
The "K" custom format specifier
string date = SelectedData.Substring(4, 11);
string s = DateTime.ParseExact(date, "MMM dd yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Okay, so i am trying to read the date/time of the Twitter feed XML, it is currently in this format: Fri May 03 15:22:09 +0000 2013 However my C# is not reading it as a Date/Time type.
This is what i got:
ArticleDate = DateTime.Parse(d.Element("created_at").Value)
created_at contains the: Fri May 03 15:22:09 +0000 2013 Format
Be careful. The times you are given back are in UTC. You may end up unintentionally letting your local time zone influence the result.
For example, one of the other answers suggested this code:
DateTime dt = DateTime.ParseExact("Fri May 03 15:22:09 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture);
The result of this on my computer, which is in Arizona (UTC-7), is:
5/3/2013 8:22:09 AM (dt.Kind == DateTimeKinds.Local)
While this is the correct moment in my local time, it is not what was given to me, and it probably not what you are expecting unless paying close attention to the .Kind property.
You can instead do the following:
DateTime dt = DateTime.ParseExact("Fri May 03 15:22:09 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
This returns:
5/3/2013 3:22:09 PM (dt.Kind == DateTimeKinds.Utc)
Which better matches what you started with.
Now, this assumes that the values coming back from Twitter will always be UTC. That seems to be the case, according to their FAQ. But one could argue that since we are given an offset, it might be more correct to use that offset as provided. If the offset ever changes, we don't want our code to break. Therefore, it is more appropriate to use the DateTimeOffset class.
DateTimeOffset dto = DateTimeOffset.ParseExact("Fri May 03 15:22:09 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture);
The result of which is:
5/3/2013 3:22:09 PM +00:00
You should be using the ParseExact of DateTime to get your value
DateTime.ParseExact("Fri May 03 15:22:09 +0000 2013","ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
Use DateTime.TryParseExact like:
if (DateTime.TryParseExact("Fri May 03 15:22:09 +0000 2013",
"ddd MMMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out ArticleDate))
{
//date is fine
}
The actual code fix for this specific date format from Twitter APi XML is below:
using System.Globalization;
CultureInfo enUS = new CultureInfo("en-US");
DateTime dateValueOut;
string userCreated = "Fri May 03 15:22:09 +0000 2013";
bool isDateFormatted = DateTime.TryParseExact(userCreated,"ddd MMM dd HH:mm:ss zzzz yyyy",enUS,DateTimeStyles.None, out dateValueOut);
if (isDateFormatted == true)
{
DateTime formattedDateTime = dateValueOut;
}
You can use
var date = DateTime.TryParseExcact(d.Element("created_at").Value, new String[]{"pattern" });
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
I have a strange problem:
string format = #"ddd MMM dd hh:mm:ss \G\M\Tzzz yyyy";
__timestamp = "Fri Apr 09 17:02:00 GMT-0500 2010";
DateTime.ParseExact(__timestamp, format, new CultureInfo("en"));
returning FormatException = "String was not recognized as a valid DateTime."
but that code going without exceptions:
string format = #"ddd MMM dd hh:mm:ss \G\M\Tzzz yyyy";
__timestamp = "Sat Apr 10 01:27:00 GMT-0500 2010";
DateTime.ParseExact(__timestamp, format, new CultureInfo("en"));
From 30k of date parsing of that format, around 50% of that failed with that exception...
Anyone know why?
it should be HH not hh. You're in the 24-hr format.
ddd MMM dd HH:mm:ss \G\M\Tzzz yyyy
Valid: Sat Apr 10 01:27:00 GMT-0500 2010
Seems that DateTime is expecting AM/PM info for that "en" format provider. Try it with any hours less than 12 (inclusive), or add some AM/PM information