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;            
}
5

3 Answers

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;

9
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");
Console.WriteLine(date);
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest