简体   繁体   中英

Formatting a Date/Time in C#

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!

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".

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

查看有关自定义日期和时间格式字符串的文档。

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM