简体   繁体   中英

Change DateTime Format as "yyyy-mm-dd"

This function is working fine but I return dd-MM-yyyy format but I want yyyy-MM-dd format

My input value is '13/5/2014 12:00:00 AM' I need change this format as '2014-5-13 00:00:00' but all the datetime variable is return in dd-mm-yyyy format I don't want to convert the date as string I want to store date value in datetime property with 'yyyy-MM-dd' format:

public DateTime DateConvertion(string Input)
{
    DateTime DateValue = DateTime.ParseExact(Input, "dd-MM-yyyy", CultureInfo.InvariantCulture);            
    return DateValue;            
}

From DateTime.ParseExact

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

In your case, they are not.

You can use dd/M/yyyy hh:mm:ss tt format instead. Here an example;

string s = "13/5/2014 12:00:00 AM";
var date = DateTime.ParseExact(s, "dd/M/yyyy hh:mm:ss tt",
                                   CultureInfo.InvariantCulture);
Console.WriteLine(date);

DateTime has no implicit format, it is just a DateTime value. You can format it as string with DateTime.ToString() method like;

date.ToString("yyyy-M-dd hh:mm:ss");

Take a look at;

public string DateConvertion(string Input)
{
    var date = DateTime.ParseExact(Input, "dd/M/yyyy hh:mm:ss tt", 
                                    CultureInfo.InvariantCulture);

    return date.ToString("yyyy-MM-dd");            
}

This would print todays date in that format

string date = DateTime.Today.ToString("yyyy-MM-dd hh:mm:ss");
Console.WriteLine(date);

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