简体   繁体   English

带有时区的时间戳格式 C#

[英]Timestamp format with Timezone C#

For the following code this will be the output (2020-06-05T23:02:24.554+05:30).对于以下代码,这将是 output (2020-06-05T23:02:24.554+05:30)。 I want the timezone without ":" in (+05:30) and expecting like (+0530).我想要(+05:30)中没有“:”的时区,并且期望像(+0530)一样。 How to achieve this with datetime formatting?如何使用日期时间格式来实现这一点? I can remove the colon with string operation but there should be some option in datetime format itself, Would be really good if someone suggest.我可以使用字符串操作删除冒号,但日期时间格式本身应该有一些选项,如果有人建议会非常好。

string date = String.Format("{0:s}.{0:fff}{0:zzz}", DateTime.Now);

There is no standard way of doing such, but you can write a customized method like with out testing that takes time and return utc as you asked for:没有这样做的标准方法,但是您可以编写一个自定义方法,例如无需测试就需要时间并按照您的要求返回 utc:

public static string GetUtc(DateTime dateTime)
{
    return $"{dateTime:zzz}".Replace(":", "");
}

And call it并称它为

GetUtc(DateTime.Now);

This will return you +0530.这将为您返回 +0530。

Btw I refer also to Get timezone from DateTime for reading as well.顺便说一句,我也参考从 DateTime 获取时区以供阅读。

You could use DateTimeOffset instead of DateTime to get what you're after.您可以使用 DateTimeOffset 而不是 DateTime 来获得您所追求的。

        var now = DateTimeOffset.Now;

        string date = string.Format("{0}{1}{2}", now.ToString("s.fff"), now.Offset.Ticks < 0 ? "-" : "+", now.Offset.ToString("hhmm"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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