简体   繁体   English

如何将字符串转换为相同格式的datetime(datetime)?

[英]How to convert string to datetime(datetime) in same format?

Here I want to convert date into string using tostring but when I convert it back, (string to datetime), the format is different. 在这里,我想使用tostring将日期转换为字符串,但是当我将其转换回(从string转换为datetime)时,格式是不同的。

 static void Main(string[] args)
    {
        string cc = "2014/12/2";
        DateTime dt = DateTime.Parse(cc);
        Console.WriteLine(dt);
        Console.ReadLine();
    }

expected output: 2014/12/2 But I get: 12/2/2014 预期输出:2014/12/2但我得到:2014/12/2

DateTime实例转换回string时,使用提供的格式调用ToString

Console.WriteLine(dt.ToString(@"yyyy/M/d");
string DateString = "06/20/1990";
IFormatProvider culture = new CultureInfo("en-US", true); 
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);

This will be your desire output 这将是您的愿望输出

udpated 过分的

string DateString = "20/06/1990";;
                IFormatProvider culture = new CultureInfo("en-US", true);
                DateTime dt = DateTime.ParseExact(DateString,"dd/mm/yyyy",culture);
                dt.ToString("yyyy-MM-dd");

try this 尝试这个

DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy", 
                              CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

use this: 用这个:

    string cc = "2014/12/2";
    DateTime dt = DateTime.Parse(cc);
    string str = dt.ToString("yyyy/M/dd"); // 2014/12/02 as you wanted
    Console.WriteLine(str);
    Console.ReadLine();

you can use 您可以使用

string formattedDate= dt.ToString("yyyy/M/d");

For reverse you can use 对于反向,您可以使用

DateTime newDate = DateTime.ParseExact("2014/05/22", "yyyy/M/d", null);

So if your expected output is like : 2014/12/2 you have to use 因此,如果您的预期输出是:2014/12/2,则必须使用

newDate.ToString("yyyy/M/d"); newDate.ToString(“ yyyy / M / d”);

As you can read here , DateTime.ToString() uses CurrentCulture to decide how to format its output ( CurrentCulture of type CultureInfo provides information on how to format dates, currency, calendar etc. It is called locale in C++). 如您在这里所读, DateTime.ToString()使用CurrentCulture决定如何格式化其输出( CultureInfo类型的CurrentCulture提供有关如何格式化日期,货币,日历等的信息。在C ++中称为语言环境 )。

Thus, the simlplest solution as suggested by previous answers, is to use an overload of ToString() which accepts a format string, effectively overriding the CurrentCulture info: 因此,前面的答案所建议的最简单的解决方案是使用ToString()的重载,该重载接受格式字符串,从而有效地覆盖CurrentCulture信息:

dt.ToString(@"yyyy/MM/dd");

More on datetime formatting can be found here . 有关日期时间格式的更多信息,请参见此处

This is simple, You just need to use date pattern during display 这很简单,您只需要在显示期间使用日期模式

string cc = "2014/12/2";
string datePatt = @"yyyy/MM/d";
DateTime dt = Convert.ToDateTime(cc);
Console.WriteLine(dt.ToString(datePatt));

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

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