Reputation: 1659
I have a date/time string that looks like the following:
Wed Sep 21 2011 12:35 PM Pacific
How do I format a DateTime to look like this?
Thank you!
Upvotes: 4
Views: 1701
Reputation: 977
Note this may be a bit crude, but it may lead you in the right direction.
Taking and adding to what Jon mentioned:
string text = date.ToString("ddd MMM dd yyyy hh:mm t");
And then adding something along these lines:
TimeZone localZone = TimeZone.CurrentTimeZone;
string x = localZone.StandardName.ToString();
string split = x.Substring(0,7);
string text = date.ToString("ddd MMM dd yyyy hh:mm t") + " " + split;
I haven't tested it, but i hope it helps!
Upvotes: 2
Reputation: 3328
string.Format("{0} {1}", DateTime.Now.ToString("ddd MMM dd yyyy HH:mm tt"), TimeZone.CurrentTimeZone.StandardName);
//Result: Wed Sep 07 2011 14:29 PM Pacific Standard Time
Trim off the Standard Time if you do not want that showing.
EDIT: If you need to do this all over the place you can also extend DateTime to include a method to do this for you.
void Main()
{
Console.WriteLine(DateTime.Now.MyCustomToString());
}
// Define other methods and classes here
public static class DateTimeExtensions
{
public static string MyCustomToString(this DateTime dt)
{
return string.Format("{0} {1}", DateTime.Now.ToString("ddd MMM dd yyyy HH:mm tt"), TimeZone.CurrentTimeZone.StandardName).Replace(" Standard Time", string.Empty);
}
}
You can run this example in LinqPad with a straight copy and paste and run it in Program mode.
MORE EDIT
After comments from below this is the updated version.
void Main()
{
Console.WriteLine(DateTime.Now.MyCustomToString());
}
// Define other methods and classes here
public static class DateTimeExtensions
{
public static string MyCustomToString(this DateTime dt)
{
return string.Format("{0:ddd MMM dd yyyy hh:mm tt} {1}", DateTime.Now, TimeZone.CurrentTimeZone.StandardName).Replace(" Standard Time", string.Empty);
}
}
Upvotes: 6
Reputation: 1499760
The bit before the time zone is easy, using a custom date and time format string:
string text = date.ToString("ddd MMM dd yyyy hh:mm t");
However, I believe that the .NET date/time formatting will not give you the "Pacific" part. The best it can give you is the time zone offset from UTC. That's fine if you can get the time zone name in some other way.
A number of TimeZoneInfo
identifiers include the word Pacific, but there isn't one which is just "Pacific".
Upvotes: 9