Formatting Date / Time in C #

I have a date / time string that looks like this:

Wed Sep 21 2011 12:35 PM Pacific 

How do I format a DateTime to look like this?

Thanks!

+4
source share
4 answers

The bit in front of the time zone is simple using a custom date and time format string :

 string text = date.ToString("ddd MMM dd yyyy hh:mm t"); 

However, I believe that formatting the .NET date and time will not give you the Pacific part. The best he can give you is the time zone offset from UTC. This is great if you can get the time zone name in some other way.

TimeZoneInfo identifiers include the word Pacific, but there is not one that is just โ€œPacificโ€.

+9
source
 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 

Turn off the standard time if you do not want to show this.

EDIT: If you need to do this everywhere, you can also extend DateTime to include a method for this.

 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 direct copy and paste and run it in program mode.

MORE EDITING

After the comments below, this is an 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); } } 
+6
source

Take a look at the docs for Custom Date and Time Format Strings .

+5
source

Please note that this can be a little rude, but it can lead you in the right direction.

Taking and adding to what John said:

 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 have not tested it, but hope this helps!

+2
source

All Articles