My problem is I have to parse a date in the format
Tue Oct 8 05:45 GMT
but what I always get using DateTime.parse() is:
system.formatexception the datetime represented by the string is not supported in calendar system.globalization.gregoriancalendar
how can this issue can be resolved?
Try this:
string format = "ddd MMM d hh:mm 'GMT'";
dateString = "Tue Oct 8 05:45 GMT";
CultureInfo provider = CultureInfo.InvariantCulture;
try
{
result = DateTime.ParseExact(dateString, format, provider);
}
catch (FormatException)
{
// Date does not conform to format defined
}
If the need for a try-catch causes you heartburn, then you can use TryParseExact(), like this:
string format = "ddd MMM d hh:mm 'GMT'";
dateString = "Tue Oct 8 05:45 GMT";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None,
out dateValue))
{
// Date conforms to format defined and result is in dateValue variable
}
else
{
// Date does not conform to format defined
}
Related
I am trying to get this date string 09 Apr 2015: 15:16:17 to display in this format 09/04/2015 15:16:17. This is what I have tried.
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
DateTime.TryParse(dateString, out dateValue);
dtDateTime = dateValue;
This is the output 01/01/0001 00:00:00
I thought the TryParse would convert the dateString value to the required DateTime format. What am I doing wrong?
You should go with this:
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, #"dd MMM yyyy':' HH':'mm':'ss",
new CultureInfo("en-us"), DateTimeStyles.None, out dateValue))
dtDateTime = dateValue;
Using TryParseExact you can provide a custom date format string to match your input date. In the example above I added that extra : after the year.
Also, you must use a CultureInfo which can understand your month name; here I assumed you got an english formatted date.
You need to specify the format since it's not a standard date format string:
DateTime.TryParseExact(
dateString,
"dd MMM yyyy: HH:mm:ss",
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out dateValue);
Also, you should check the result of the call since TryParse and TryParseExact return true/false
You can use TryParseExact method:
DateTime.TryParseExact(dateString, "dd MMM yyyy: HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AllowWhiteSpaces,
out dtDateTime);
Tips:
If you use MMM, the month will be treated as if it is in 3 letter format (like Apr )
If you use HH rather than hh it means the hour part is in 24-hour format, the it will not fail on parsing 15 as hour
I have devexpress dateedit object and I send selected date to controller from clientside but i cant convert my string date value to datetime value
When I try I get this error => string was not recognized as a valid DateTime
my string date value => Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)
Convert Code =>
DateTime startDate = DateTime.ParseExact(sDate, "ddd MMM d yyyy HH:mm:ss zzzz", CultureInfo.InvariantCulture);
How should I do format this string ?
You need to "escape" unrecognized symbols with single quote:
var sDate = "Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var format = "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz '(Turkey Daylight Time)'";
DateTime startDate = DateTime.ParseExact(sDate, format, CultureInfo.InvariantCulture);
Console.WriteLine(startDate);
prints:
8/28/2014 12:00:00 AM
Works well with single d in third group, added one just for clarity.
Single or double quotes denote Literal string delimiter. You can read and check more examples at this msdn article on DateTime formats
First convert date string to date and then date to ISO and send it to server. That would work.
var date = new Date("Thu Aug 28 2014 00:00:00 GMT+0300")
var sDate = date.toISOString();
Try removing the unknown format with Regex first.
var sDate = #"Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var sDateOnly = Regex.Replace(sDate, #"\s*(\(.*\))", m => string.Empty);
var f = #"ddd MMM d yyyy HH:mm:ss \G\M\Tzzzz";
DateTime startDate = DateTime.ParseExact(sDateOnly, f, CultureInfo.InvariantCulture);
This question already has answers here:
C# to Convert String to DateTime
(6 answers)
Closed 9 years ago.
I am extracting the data from an api and I am getting this value "Fri Aug 16 21:06:52 +0000 2013" I would like to know how I would be able to change this string value to type Date time
Use DateTime.ParseExact or (if the input may be invalid) DateTime.TryParseExact:
string input = "Aug 16 21:06:52 +0000 2013";
DateTime output;
if (DateTime.TryParseExact(input, "MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out output))
{
// date was parsable, here is it:
Console.WriteLine(output.ToLongDateString());
}
Custom Date and Time Format Strings, especially the "zzz" Custom Format Specifier
You can use DateTime.ParseExact
DateTime.ParseExact("Aug 16 21:06:52 +0000 2013", "MMM dd HH:mm:ss +ffff yyyy",
System.Globalization.CultureInfo.InvariantCulture);
You should read DateTime custom formats.
this should solve your problem thougf it
DateTime result = DateTime.ParseExact("Aug 16 21:06:52 +0000 2013", "MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
or to do it more appropriately and avoid exceptions. Do it like this
//zzz is Hours and minutes offset from UTC
string[] formats = { "MMM dd HH:mm:ss zzz yyyy" };
DateTime result;
string date = "Aug 16 21:06:52 +0000 2013";
if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
// i prefer this method though
}
Parsing string to datetime:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
DateTime.TryParse() returns true or false for success / fail.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
DateTime.Parse() throws an exception on failure.
There are a few ways...
DateTime.TryParse
DateTime dt;
if (DateTime.TryParse("Aug 16 21:06:52 +0000 2013", out dt))
{
//parsing was successfull
}
This won't throw an exception if the parse fails.
Then there is DateTime.Parse:
DateTime dt = DateTime.Parse("Aug 16 21:06:52 +0000 2013");
Unlike TryParse, this will throw an exception if parsing fails.
And there is also, Convert.ToDateTime:
DateTime dt = Convert.ToDateTime("Aug 16 21:06:52 +0000 2013", culture);
This also throws an error if the conversion fails.
Edited after you updated your question.
If you want it converted to your local time zone, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture);
Otherwise, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss zzz yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
If the +0000 is always like that in the input, and you want to disregard that completely, use:
var dateTime = DateTime.ParseExact("Fri Aug 16 21:06:52 +0000 2013",
"ddd MMM dd HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
i have a string date in the following format
Thu Jan 5 19:58:58 2012
I need to parse this string to System.DateTime TimeReceived variable using DateTime.Parse() method.
Any one knows how to parse this string?
You could use the TryParseExact method which allows you to specify a format:
var str = "Thu Jan 5 19:58:58 2012";
DateTime date;
if (DateTime.TryParseExact(str, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
// the date was successfully parsed, you could use the date variable here
Console.WriteLine("{0:HH:mm:ss dd/MMM/yy}", date);
}
if you look at the ParseExact function, about halfway there's
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
so if you'd switch those around to match what you want, you'll end up with
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date and time with custom specifier.
dateString = "Thu 5 Jan 19:58:58 2012";
format = "ddd MMM dd hh:mm:ss yyyy";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
var reformatted = input.Substring(4, 17) + input.Substring(22);
return DateTime.Parse(reformatted);
That should work fine.
I have a program which converts a irregular date and time string into a system DateTime.
However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.
There are only 2 types of date time strings that the program needs to convert:
Thu Dec 9 05:12:42 2010
Mon Dec 13 06:45:58 2010
Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.
May someone please advise on the codes? Thanks!
The codes:
String rb = re.Replace(" ", " 0");
DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);
Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
I would really avoid regex and use what's already built-in .NET (TryParseExact method and date formats):
DateTime result;
string dateToParse = "Thu Dec 9 05:12:42 2010";
string format = "ddd MMM d HH:mm:ss yyyy";
if (DateTime.TryParseExact(
dateToParse,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AllowWhiteSpaces,
out result)
)
{
// The date was successfully parsed => use the result here
}
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.
You can use this Regex statement with named groups to make it easier
((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
This is sample code which you can try:
var str = "Thu Dec 9 06:45:58 2010";
if (str.IndexOf(" ") > -1)
{
str = str.Replace(" ", " ");
DateTime time = DateTime.ParseExact(str, "ddd MMM d hh:mm:ss yyyy", null);
}
else
{
DateTime time = DateTime.ParseExact(str, "ddd MMM dd hh:mm:ss yyyy", null);
}