I need help to convert current date to "Tue Nov 4 00:00:00 UTC+0530 2014" date format using C#.
Say I have date like : DateTime dt = DateTime.Now;
Now, how can I convert it in mentioned format.
I need help to convert current date to "Tue Nov 4 00:00:00 UTC+0530 2014" date format using C#.
Say I have date like : DateTime dt = DateTime.Now;
Now, how can I convert it in mentioned format.
DateTime.ToString(string)
allows you to specify a format for your date. You can construct a custom format using Custom Date and Time Format Strings.
I feel like taking risk to answer your question but anyway..
A DateTime
doesn't have any
implicit format. It just have date and time values etc.. That's why it is not possible to have any format. But string
representations of them can have a format. Formatting a DateTime
is easy, just need to use DateTime.ToString()
method with a specific culture. (In your case looks like InvariantCulture
is a good candidate)
DateTime dt = DateTime.Now;
dt.ToString("ddd MMM d HH:mm:ss 'UTC+0530' yyyy", CultureInfo.InvariantCulture);
returns
Tue Nov 4 14:20:36 UTC+0530 2014
AFAIK, time zone abbreviations are not standardized and that's why there is way to parse them besides literal string delimiter. Also since a DateTime
doesn't keep offset value, you need also parse it as a literal string delimiter
If you would want to +05:30
instead +0530
as a result, "zzz"
custom format specifier would be a nice choice since it gets +
or -
sign, hours and minutes part offset of local operating system's time zone from UTC
.
Based upon your suggestions, I build this code
DateTimeOffset localTime = DateTimeOffset.Now;
string.Format("{0:ddd MMM d HH:mm:ss} UTC+{1} {0:yyyy}", localTime, localTime.Offset.ToString("hhmm"));
and its generating correct format: "Tue Nov 4 18:25:48 UTC+0530 2014"