I need to parse the string
Sat, 14 Jan 2017 12:12:12 Europe/Warsaw
to DateTime
I've tried:
var datestring = "Sat, 14 Jan 2017 12:12:12 Europe/Warsaw";
DateTime.TryParse(datestring, out expDt);
but it's not working.
Thanks in advance for any help.
I think you can do something like this:
string datestring = "Sat, 14 Jan 2017 12:12:12 Europe/Warsaw";
// remove "Europe/Warsaw" because it wont be used.
datestring = datestring.Substring(0, datestring.LastIndexOf(' '));
// now datestring looks like "Sat, 14 Jan 2017 12:12:12"
// so you should adapt the format:
string dateFormat = "ddd, dd MMM yyyy HH:mm:ss";
// now you can use DateTime.ParseExact to retrieve DateTime object
DateTime dt = DateTime.ParseExact(datestring, dateFormat, System.Globalization.CultureInfo.InvariantCulture);
This should parse to correct DateTime object.
Calling dt.ToString() should return something like 14.01.2017 12:12:12
EDIT:
For everyone else that assumes that DateTime object is somewhat aware of TimeZone or is it dependant on it. Please read this answer Get timezone from DateTime
That's why for me it was useless to extract TimeZone from the string. Because it would have no impact on DateTime object itself. If ( but I doubt that ) someone has the same issue and need this informations then here's the example :
string datestring = "Sat, 14 Jan 2017 12:12:12 Europe/Warsaw";
// remove "Europe/Warsaw" because it wont be used.
string datestr = new string(datestring.Take(datestring.LastIndexOf(' ')));
// now datestring looks like "Sat, 14 Jan 2017 12:12:12"
// so you should adapt the format:
string dateFormat = "ddd, dd MMM yyyy HH:mm:ss";
// now you can use DateTime.ParseExact to retrieve DateTime object
DateTime dt = DateTime.ParseExact(datestring, dateFormat, System.Globalization.CultureInfo.InvariantCulture);
string timezonestr = new string(datestring.Skip(datestring.LastIndexOf(' ') + 1));
try {
TimeZoneInfo timzeone = TimeZoneInfo.FindSystemTimeZoneById(timezonestr);
} catch { /* probably an error because there's no timezone called Europe/Warsaw */ }
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);
I have the below string which I need to parse to a DateTime:
Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)
I am unsure what format to supply to my DateTime.ParseExact to achieve this. The nearest I could find in standard date/time format string was Full date/time pattern (long time) as below but this does not work
DateTime.ParseExact("Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)", "F", CultureInfo.InvariantCulture); // FormatException
Any ideas?
If the offset is not important, I suggest you just truncate the string after the time.
It looks like the format should allow that by finding the first space after position 16 (the start of the time in your example; part way through the time if the day number is shorter):
int endOfTime = text.IndexOf(' ', 16);
if (endOfTime == -1)
{
throw new FormatException("Unexpected date/time format");
}
text = text.Substring(0, endOfTime);
DateTime dateTime = DateTime.ParseExact(text, "ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(I'm assuming the month and day names are always in English.)
If you are certain it will always be GMT summer time, couldnĀ“t you use this:
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)";
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K' (GMT Summer Time)'";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);
Or if summer/winter can change but always GMT, regardless of offset.
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)".Split('(')[0].Trim();
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);
I am having an issue converting this date format into another format. I was hoping that somebody on here would be able to help me out.
Here is my code:
string fromFormat = "ddd, dd MM yyyy HH:mm:ss zzz";
string toFormat = "yyyy-MM-dd";
DateTime newDate = DateTime.ParseExact("Mon, 25 03 2013 00:00:00 GMT", fromFormat, null);
Console.WriteLine(newDate.ToString(toFormat));
-------EDIT--------
I was able to get rid of my errors by changing the day from 22 to 25. My new issue is trying to get the timezone to convert from GMT to EST. Would anyone have any ideas?
-------EDIT #2-------
Here is my current code as it stands. I am still having issues with a timezone conversion.
var date = "Mon, 25 03 2013 00:00:00 GMT";
// Cuts off "GMT" portion of string
string newdate = date.Substring(0, 24);
// Switches the output of date
string fromFormat = "ddd, dd MM yyyy HH:mm:ss";
string toFormat = "yyyy-MM-dd";
DateTime newDate = DateTime.ParseExact(newdate, fromFormat, null);
string finaldate = newDate.ToString(toFormat);
// Output final date
Console.WriteLine(finaldate);
-------EDIT #3-------
The code:
var input = "Mon, 25 03 2013 00:00:00 GMT";
var inner = input.Substring(0, 24);
var format = "ddd, dd MM yyyy HH:mm:ss";
var zoneId = "Eastern Standard Time";
var parsed = DateTime.ParseExact(inner, format, CultureInfo.InvariantCulture);
var utcDateTime = DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
var eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, zoneId);
Console.WriteLine(eastern);
The error:
Unhandled Exception: System.TimeZoneNotFoundException: Exception of type
'System.TimeZoneNotFoundException' was thrown.
at System.TimeZoneInfo.FindSystemTimeZoneByFileName (System.String id, System.String
filepath) [0x00000] in :0
at System.TimeZoneInfo.FindSystemTimeZoneById (System.String id) [0x00000] in :0
at System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId (DateTime dateTime, System.String
destinationTimeZoneId) [0x00000] in :0
at Program.Main () [0x00000] in :0
Any help would be much appreciated! Thanks!
-------FINAL EDIT-------
This is what ended up changing the timezone and converting to the format that I needed. Special thanks to #MattJohnson for all of his help!
// Cuts off 'GMT' portion of string
var newdate = date.Substring(0, 24);
var fromFormat = "ddd, dd MM yyyy HH:mm:ss";
var toFormat = "yyyy-MM-dd";
var zoneId = "Eastern Standard Time";
var parsed = DateTime.ParseExact(newdate, fromFormat, CultureInfo.InvariantCulture);
// Specifies UTC time and converts it to EST timezone
var utcDateTime = DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
var eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, zoneId);
// Converts date to final format needed
var finaldate = eastern.ToString(toFormat);
string fromFormat = "ddd, dd MM yyyy HH:mm:ss zzz";
The error is your zzz, it is expecting the numerical representation of the timezone, not the abbreviation of the timezone.
So a acceptable version would be
DateTime newDate = DateTime.ParseExact("Mon, 22 03 2013 00:00:00 +0:00", fromFormat, null);
but that would throw a different FormatExecption with the message "String was not recognized as a valid DateTime because the day of week was incorrect." If you make the Monday to Friday correction the parse works
DateTime newDate = DateTime.ParseExact("Fri, 22 03 2013 00:00:00 +0:00", fromFormat, null);
I don't think there is a format specifier that can take in the textual abbreviation version of the timezone.
As others pointed out, the input value you have is self-inconsistent. It refers to a March 22 2013 as a Monday when it is actually a Friday. So you should go back to your source data and figure out why that happens. I'm sure you have heard the saying, "Garbage In, Garbage Out".
If you are sure you want to ignore the day of week, and you are certain that the time zone will always be GMT, then you can do this:
var input = "Mon, 22 03 2013 00:00:00 GMT";
var inner = input.Substring(5, 19);
var format = "dd MM yyyy HH:mm:ss";
var parsed = DateTime.ParseExact(inner, format, CultureInfo.InvariantCulture);
var utcDateTime = DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
Note that I explicitly set the kind to UTC, because you are bringing in GMT values. GMT and UTC are identical for all practical purposes.
If it's possible that other time zone values will be passed, then please provide a sampling of different possible inputs and perhaps we can find a way to accommodate that.
As an aside - this string looks very similar to RFC822/RFC1123 formatted dates, except you are passing the month as a number instead of one of the three-letter abbreviations. Did you do this intentionally? If so, you have broken the spec for this format. If your intention was to remove potentially localizable strings from the data, then please use a format that is already designed for that, such as ISO8601/RFC3339.
On Time Zones
You said you want to convert to EST, You probably mean "US Eastern Time", which alternates between EST and EDT for daylight saving time. Despite this, the Windows Time Zone database uses the id of "Eastern Standard Time" to refer to both values - so try not to get confused on that point.
Once you have the date as a DateTime of Utc kind, as I showed above, you can convert that to Eastern Time with the following:
var zoneId = "Eastern Standard Time"; // don't get confused here! :)
var eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTime, zoneId);
Just be careful what you do with this value. If you are displaying it to an user, then you are ok. Just do this:
var s = eastern.ToString("g"); // or whatever format you want.
But if you do math with this, or store it as an recorded event time, you are potentially introducing errors into your results. This is due to daylight saving time transitions. One way to avoid this is to use a DateTimeOffset type instead:
var utcDateTimeOffset = new DateTimeOffset(utcDateTime, TimeSpan.Zero);
var eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDateTimeOffset, zoneId);
Now when you work with these values, any ambiguities are captured by the offset.
If this seems very confusing to you, don't worry - you're not alone. You might want to try using Noda Time instead. It will prevent you from shooting yourself in the foot.
To see what's wrong, print a DateTime using your fromString:
DateTime dt = new DateTime(2013, 3, 22);
string s = dt.ToString(fromFormat);
you'll see that the output is:
Fri, 22 03 2013 00:00:00 -04:00
so that is the format it would be expecting.
You might be able to get some help on the abbreviations from this article.
There are two issues:
1) The day selected was a Friday not a Monday
2) The 'zzz' wants a plus or minus 0:00
So, to get it to work would be:
string fromFormat = "ddd, dd MM yyyy HH:mm:ss zzz";
string toFormat = "yyyy-MM-dd";
DateTime newDate = DateTime.ParseExact("Fri, 22 03 2013 00:00:00 +0:00", fromFormat, null);
Console.WriteLine(newDate.ToString(toFormat));
There's no simple, built-in way to convert from a Time Zone abbreviation to an offset or proper name. This is discussed in this topic here:
Timezone Abbreviations
You'll either need to create a table of the abbreviations you want to use, mapped to an offset or proper name, or you'll need to change the format of your incoming date/time string to use offsets.
string fromFormat = "ddd, dd MM yyyy HH:mm:ss zzz";
string toFormat = "yyyy-MM-dd";
DateTime newDate = DateTime.ParseExact("Mon, 22 03 2013 00:00:00 +00:00", fromFormat, null);
Console.WriteLine(newDate.ToString(toFormat));
22 03 2013 00:00:00 GMT is not Monday it's Friday
try
string fromFormat = "ddd, dd MM yyyy HH:mm:ss zzz";
string toFormat = "yyyy-MM-dd";
Console.WriteLine(DateTime.ParseExact("Fri, 22 03 2013 00:00:00 +00:00", fromFormat,
CultureInfo.InvariantCulture).ToString(toFormat));
I have a date string, returned from a ExtJS datetime picker, which looks like this:
Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)
From this I would need to have it in this format : YYYY-mm-dd, using C# or JavaScript.
How could I do this? I've tried using DateTime.Parse and it cannot be parsed.
Any idea?
You don't seem to care about the time and timezone information so you can in fact use DateTime.ParseExact to parse the date. Assuming that the day of month part may be just a single digit (e.g. 2012-04-01 is Sun Apr 1 2012) the pattern you need to use is ddd MMM d yyyy.
The "hardest" part is really chopping of the time and timezone part. If the day of month is a single digit you have to take of substring of length 14; otherwise of length 15. Here is a way to get the index of the 4th space character in a string:
var str = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)";
var index = -1;
for (var i = 0; i < 4; i += 1)
index = str.IndexOf(' ', index + 1);
You can then parse the date into a DateTime:
var date = DateTime
.ParseExact(str.Substring(0, index), "ddd MMM d yyyy", CultureInfo.InvariantCulture);
This can be formatted back into a string using whatever format and culture you need.
In .NET, where you have a string representation of a date that has a guaranteed format, you can use DateTime.ParseExact to parse it:
var input = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)"
.Substring(0, 15);
var format = "ddd MMM dd YYYY";
var date = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);
// Now date is a DateTime holding the date
var output = date.ToString("yyyy-MM-dd");
// Now output is 2012-04-25
May be this can help you Click
try this using Javascript.
var d = new Date('Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)');
var curr_day = d.getDate();
var curr_month = ('0'+(d.getMonth()+1)).slice(-2)
var curr_year = d.getFullYear();
var new_date = curr_year+"-"+curr_month+"-"+curr_day;
In JavaScript
new Date("Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)")
Will give you a date object. You can then format it to your date format (or preferably ISO8601, or milliseconds from the epoc using .getTime()) by picking out the (UTC) year, month and day