[英]Convert s string to specific DateTime format with timezone - C#
I am trying this code (c#):我正在尝试这段代码 (c#):
string input1 = "2009-11-22 01:01:05 +1:30"
string input2 = "2009-11-22 01:01:05"
DateTime date1 = new DateTime();
DateTime date2 = new DateTime();
string format = "yyyy-MM-dd hh:mm:ss [z]"
DateTime orgDate1 = DateTime.ParseExact(input1, format, null);
DateTime orgDate2 = DateTime.ParseExact(input2, format, null);
The purposes are:目的是:
string input1 = "2009-11-22 01:01:05 +1:30"
DateTime date1 = new DateTime();
string format = "yyyy-MM-dd hh:mm:ss zzz"
DateTime orgDate1 = DateTime.ParseExact(input1, format, null);
I tried many options, like:我尝试了很多选择,例如:
DateTime.ParseExact("2009-11-22 00:00:00 1", "yyyy-MM-dd hh:mm:ss z",null)
DateTime.ParseExact("2009-11-22 00:00:00 1", "yyyy-MM-dd hh:mm:ss Z",null)
But always get formatException.但总是得到 formatException。
Only this code works:只有这段代码有效:
DateTime.ParseExact("2009-11-22 00:00:00Z", "yyyy-MM-dd hh:mm:ssZ",null)
But it returns the exact UTC time zone while I need to get it as parameter.但它返回确切的 UTC 时区,而我需要将它作为参数。
all is described above都在上面描述了
Ok, after several trials I find that following code works:好的,经过多次试验,我发现以下代码有效:
DateTime.ParseExact("2009-11-22 00:00:00+1", "yyyy-MM-dd hh:mm:ss z",null)
So remain the other Q - how can I define the format with optional timezone, such that both "2009-11-22 00:00:00+1" and "2009-11-22 00:00:00" will be parsed properly?所以保留另一个问题 - 我如何定义带有可选时区的格式,以便正确解析“2009-11-22 00:00:00+1”和“2009-11-22 00:00:00” ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.