Formatting a Date/Time in C#

2019-06-25 08:28发布

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!

4条回答
聊天终结者
2楼-- · 2019-06-25 09:06

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

查看更多
Summer. ? 凉城
3楼-- · 2019-06-25 09:18
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);
    }
}
查看更多
ら.Afraid
4楼-- · 2019-06-25 09:27

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!

查看更多
forever°为你锁心
5楼-- · 2019-06-25 09:29

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

查看更多
登录 后发表回答