Reputation: 6622
i am trying to format the date to this format. 01/20/2013 02:30PM EDT, using this
LastModified.ToString("MM/dd/yyyy HH:mmtt");
but the result is coming like this
01-20-2013 02:30PM
dont know why it is showing '-'
instead '/'
.
Also, for timezome, it seems there is only format available like +02:00
. But I want timezone as string, i could not find any format for this, how can I get is as string like EDT/PST/IST etc?
Upvotes: 0
Views: 215
Reputation: 1503270
From the MSDN page on custom date and time format strings:
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfoDateSeparator property of the current or specified culture.
If you want it to definitely use /
, you should either use the invariant culture, or quote the slash ("MM'/'dd'/'yyyy hh':'mmtt"
). Note that I've quoted the time separator as well, as that can vary by culture too. I've also changed it to use the 12 hour clock, as per Arshad's answer.
When using a custom date/time format, you should probably use the invariant culture anyway. (For example, it seems odd to use a UK culture to format the string in a US-centric way - today would normally be represented as 02/05/2013 in the UK, not 05/02/2013.)
In terms of a time zone specifier - I don't know any way to use the time zone abbrevation within date/time formatting. I would personally advise against using abbreviations anyway, as they can be ambiguous and confusing. I can't see anything within TimeZoneInfo
which even exposes that information for you to manually add it.
(It's possible that in Noda Time we'll support formatting with the abbreviation, but probably not parsing, precisely because of the ambiguity.)
Upvotes: 4
Reputation: 9862
i have found one mistake is that ,HH
means time in 24 HRS format. You can try
string date = "01/20/2013 02:30PM";
DateTime dtTime;
if (DateTime.TryParseExact(date, "MM/dd/yyyy hh:mmtt",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
Upvotes: 2
Reputation: 12934
Formatting of DateTime is influenced by your Culture and your format string. Your current culture (Thread.CurrentThread.CurrentCulture
) uses the -
as the default seperator of your date components.
The Culture of India uses -
and since you are from Inda, it would make sence (see: http://en.wikipedia.org/wiki/Date_and_time_notation_in_India)
Two options:
/
by default as seperator. For example: LastModified.ToString("MM/dd/yyyy HH:mmtt", new CultureInfo("en-US"));
\
. For example: For example: LastModified.ToString("MM\/dd\/yyyy HH:mmtt");
See also: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Upvotes: 0