[英]Convert from timezone datetime to short date C#
I have datetime data that looks like this: 2018-06-29T22:10:33Z
. 我的日期时间数据如下所示:
2018-06-29T22:10:33Z
。
I need it in Short date format - 06/29/2018
ie, without the time part. 我需要短日期格式 -
06/29/2018
即没有时间部分。
I have tried the following in C#: 我在C#中尝试过以下内容:
ConvertToDateTime(dateString);
DateTime.Parse(dateString);
Errors with both. 两者都有错误。
I'm resorting to dateString.substring(0,10)
to get the 1st 10 characters and convert that to date. 我正在使用
dateString.substring(0,10)
获取前10个字符并将其转换为日期。
Is there a better method? 有更好的方法吗?
You can use DateTime.TryParse method. 您可以使用DateTime.TryParse方法。 ie:
即:
string s = "2018-06-29T22:10:33Z";
DateTime t;
if (DateTime.TryParse(s, out t))
{
Console.WriteLine(t.ToShortDateString());
}
To get UTC date: 要获得UTC日期:
string s = "2018-06-29T22:10:33Z";
DateTime t;
if (DateTime.TryParse(s, out t))
{
Console.WriteLine(t.ToUniversalTime().ToShortDateString());
}
First and foremost, the date format appears to be not well formatted. 首先,日期格式似乎格式不正确。 The format you should be receiving should like "yyyy-MM-ddTHH:mm:ss.fffffffK" (ie "2018-06-29T22:10:05.1440844Z").
您应该接收的格式应该是“yyyy-MM-ddTHH:mm:ss.fffffffK”(即“2018-06-29T22:10:05.1440844Z”)。
Assuming there was a typo in the sample date provided, here are a couple of samples to convert the date time string (in UTC format) to a DateTime: 假设提供的样本日期中有一个拼写错误,这里有几个样本将日期时间字符串(以UTC格式)转换为DateTime:
var dateString = "2018-06-29T22:10:05.1440844Z";
var datetime = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:ss.fffffffK", CultureInfo.InvariantCulture);
var date = datetime.Date;
or 要么
var datetime = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture);
var date = datetime.Date;
You have to take into consideration that you are getting a UTC date and timezone conversions must be taken into consideration. 您必须考虑到您要获得UTC日期和时区转换必须考虑在内。 Also, when just taking the date part, the time part is set to "12:00:00 AM".
此外,当刚刚拍摄日期部分时,时间部分被设置为“12:00:00 AM”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.