Formatting a Date/Time in C#

拈花ヽ惹草 提交于 2019-12-10 17:12:46

问题


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!


回答1:


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




回答2:


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



回答3:


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




回答4:


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!



来源:https://stackoverflow.com/questions/7340621/formatting-a-date-time-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!