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);