[英]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? 如何将DateTime格式化为这样?
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. 但是,我相信.NET日期/时间格式不会给你“太平洋”部分。 The best it can give you is the time zone offset from UTC.
它能给你的最好的是与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". 许多
TimeZoneInfo
标识符包含单词Pacific,但没有一个只是“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. 编辑:如果您需要在整个地方执行此操作,您还可以扩展DateTime以包含一个方法来为您执行此操作。
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. 您可以在LinqPad中运行此示例,直接复制并粘贴并在程序模式下运行它。
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: 采取并添加Jon提到的内容:
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! 我没有测试过,但我希望它有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.