关于c#:将DateTime格式更改为” yyyy-mm-dd”

Change DateTime Format as “yyyy-mm-dd”

此功能正常工作,但我返回dd-MM-yyyy格式,但我想要yyyy-MM-dd格式

我的输入值为'13 / 5/2014 12:00:00 AM',我需要将此格式更改为'2014-5-13 00:00:00',但是所有datetime变量都以dd-mm- yyyy格式我不想将日期转换为字符串,我想以'yyyy-MM-dd'格式在datetime属性中存储日期值:

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


来自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.

在您的情况下,不是。

您可以改用dd/M/yyyy hh:mm:ss tt格式。这里是一个例子;

1
2
3
4
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没有隐式格式,它只是一个DateTime值。您可以使用DateTime.ToString()这样的方法将其格式化为string;

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

看看;

  • 自定义日期和时间格式字符串


1
2
3
4
5
6
7
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");            
}