简体   繁体   English

将日期时间格式更改为“yyyy-mm-dd”

[英]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此功能工作正常,但我返回 dd-MM-yyyy 格式但我想要 yyyy-MM-dd 格式

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:我的输入值为 '13/5/2014 12:00:00 AM' 我需要将此格式更改为 '2014-5-13 00:00:00' 但所有日期时间变量都以 dd-mm-yyyy 格式返回我不想将日期转换为字符串我想以“yyyy-MM-dd”格式将日期值存储在日期时间属性中:

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

From DateTime.ParseExact 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. 使用指定的格式和特定​​于区域性的格式信息,将日期和时间的指定字符串表示形式转换为其等效的DateTime。 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. 您可以改用dd/M/yyyy hh:mm:ss tt格式。 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. DateTime没有隐式格式,它只是一个DateTime值。 You can format it as string with DateTime.ToString() method like; 您可以使用类似DateTime.ToString()方法将其格式化为string

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);

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

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