如何将日期时间转换为包含时区的datetime对象或字符串 [英] How to convert date time into datetime object or string which contains the time zone

查看:536
本文介绍了如何将日期时间转换为包含时区的datetime对象或字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期格式转换为格式

dd MMM yyyy HH:mm:ss.fff

其中包含时区,但它给我的错误就像字符串没有有效的日期时间格式。



我尝试过:



 string dts =星期六,2017年9月16日06:14:33 -0700(PDT); 

DateTime dtime = DateTime.ParseExact(dts,dd MMM yyyy HH:mm:ss.fff,CultureInfo.InvariantCulture);

使用正则表达式使用DateTime.TryParseExact:

  string  inp =  星期六,2017年9月16日06:14:33 -0700(PDT); 
DateTime dt;
string noTzName = Regex.Replace(inp, @ (\d\d)(\\\)\(\w + \) < span class =code-string>


1:


2)。Trim();
string dtFormat = ddd,dd MMM yyyy HH:mm:ss zz;
if (DateTime.TryParseExact(inp,dtFormat,CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}


I am trying to convert date to format

"dd MMM yyyy HH:mm:ss.fff"

which contains the time zone, but it is giving me error like string was not in valid datetime format.

What I have tried:

 string dts = "Sat, 16 Sep 2017 06:14:33 -0700 (PDT)";

DateTime dtime =DateTime.ParseExact(dts , "dd MMM yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture);

解决方案

Use DateTime.TryParseExact with a regex:

string inp = "Sat, 16 Sep 2017 06:14:33 -0700 (PDT)";
            DateTime dt;
            string noTzName = Regex.Replace(inp, @"(\d\d)(\d\d) \(\w+\)", "


1:


2").Trim(); string dtFormat = "ddd, dd MMM yyyy HH:mm:ss zz"; if (DateTime.TryParseExact(inp, dtFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { Console.WriteLine(dt); }


这篇关于如何将日期时间转换为包含时区的datetime对象或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆