简体   繁体   中英

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.

My string is in yyyy-MM-dd HH:mm format.

I was trying TryParseExact and specifying the culture also but I just couldn't understand that how it works. Below is the code that I am trying and my item.CreationDate is in "yyyy-MM-dd HH:mm" format

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.

When you convert a string to DateTime you must state what format the input is in (as you have). 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 .

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. In my case I used 'en-GB'. Here's a list of the accepted culture codes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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