简体   繁体   English

如何从字符串转换为系统日期时间格式?

[英]How to convert to system datetime format from a string?

I need to convert a string datetime format to a DateTime field which should be in system Datetime format?我需要将字符串日期时间格式转换为应为系统日期时间格式的日期时间字段? I've tried Convert.ToDateTime, DateTime.Parse, DateTime.ParseExact but all of them convert to dd-MM-yyyy HH:mm:ss format.我尝试过 Convert.ToDateTime、DateTime.Parse、DateTime.ParseExact,但它们都转换为dd-MM-yyyy HH:mm:ss格式。

My string is in yyyy-MM-dd HH:mm format.我的字符串是yyyy-MM-dd HH:mm格式。

I was trying TryParseExact and specifying the culture also but I just couldn't understand that how it works.我正在尝试 TryParseExact 并指定文化,但我无法理解它是如何工作的。 Below is the code that I am trying and my item.CreationDate is in "yyyy-MM-dd HH:mm" format下面是我正在尝试的代码,我的 item.CreationDate 采用“yyyy-MM-dd HH:mm”格式

DateTime dateTime;  
bool isSuccess1 = DateTime.TryParseExact(item.CreationDate, "yyyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime);
DateTime result = dateTime;

Thanks in advance.提前致谢。

Can it be this easy?能这么容易吗? - yyyyy-MM-dd HH:mm has 5 y s in your example, not 4. - yyyyy-MM-dd HH:mm在您的示例中有 5 y s,而不是 4。

When you convert a string to DateTime you must state what format the input is in (as you have).当您将字符串转换为 DateTime 时,您必须 state 输入的格式(如您所见)。 If the conversion succeeded the DateTime object will hold the data for all the date parts (years, months, days etc.) and if you want to view them as a date again you must state what format you want to see them in. When using DateTime.TryParseExact it's worth noting that if the conversion fails it will set the value to the DateTime.MinValue .如果转换成功,DateTime object 将保存所有日期部分(年、月、日等)的数据,如果您想再次将它们视为日期,则必须 state 以什么格式查看它们。使用时DateTime.TryParseExact值得注意的是,如果转换失败,它将将该值设置为DateTime.MinValue

There are various ways of showing the date again.有多种方法可以再次显示日期。 The most common is stating the custom format for the date as a string.最常见的是将日期的自定义格式声明为字符串。 Another way is to use a standard format .另一种方法是使用标准格式

var creationDate = "2020-04-13 13:23";

DateTime.TryParseExact(creationDate, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateTime);

var myCulture = new CultureInfo("en-GB");

if(dateTime > DateTime.MinValue)
{
    Console.WriteLine("Your custom format date is: " + dateTime.ToString("yyyy-MM-dd HH:mm"));
    Console.WriteLine("Your standard format date is: " + dateTime.ToString("g", myCulture));
}

When you put this into a console app the results are like this:当您将其放入控制台应用程序时,结果如下所示:

在此处输入图像描述

With some of the standard format ones you will need to define the culture as it will be different for something like the en-US compared to something like zh-CN.对于一些标准格式,您需要定义文化,因为与 zh-CN 之类的内容相比,en-US 之类的内容会有所不同。 In my case I used 'en-GB'.就我而言,我使用了“en-GB”。 Here's a list of the accepted culture codes . 这是接受的文化代码列表

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

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