简体   繁体   English

将字符串日期转换为特定的日期时间格式

[英]Converting string date into specific date time format

I have a date time format in a string like following: 我有一个字符串形式的日期时间格式,如下所示:

start date: 开始日期:

2018/06/30 23:00

and end date: 和结束日期:

2018/07/01 19:32

And now I would like to convert this string into format like this: 现在,我想将此字符串转换为如下格式:

2017-02-11T19:58:18.918Z

Both the start and end date should be in this date - string format 开始日期和结束日期都应在此日期中-字符串格式

I have tried something like this: 我已经尝试过这样的事情:

   var properStart = DateTimeOffset.ParseExact(startdate, "yyyy-MM-dd'T'HH:mm:sszzz",
                                                       CultureInfo.InvariantCulture).ToString();
   var properEnd = DateTimeOffset.ParseExact(enddate, "yyyy-MM-dd'T'HH:mm:sszzz",
                                                CultureInfo.InvariantCulture).ToString();

But this gives me an error like following: 但这给我一个错误,如下所示:

Additional information: String was not recognized as a valid DateTime.

What am I doing wrong here?? 我在这里做错了什么?

You're trying to parse this string: 您正在尝试解析此字符串:

"2018/06/30 23:00"

Specifying this format: 指定此格式:

"yyyy-MM-dd'T'HH:mm:sszzz"

That format doesn't match that string, so the parsing fails. 该格式与该字符串不匹配,因此解析失败。 Parse from the format that the input is in: 根据输入的格式进行解析:

var properStart = DateTimeOffset.ParseExact(startdate, "yyyy/MM/dd HH:mm",
                                                   CultureInfo.InvariantCulture)

Then output into the format you want: 然后输出为所需的格式:

var properStartOutput = properStart.ToString("yyyy-MM-dd'T'HH:mm:sszzz");

Or, if you really want it all in one line: 或者,如果您真的想要全部放在一行中:

var properStart = DateTimeOffset.ParseExact(startdate, "yyyy/MM/dd HH:mm",
                                                   CultureInfo.InvariantCulture).ToString("yyyy-MM-dd'T'HH:mm:sszzz").

The point is that parsing input and formatting output are two different operations. 关键是解析输入格式化输出是两个不同的操作。

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

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