Here I want to convert date into string using tostring
but when I convert it back, (string to datetime), the format is different.
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
将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
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++).
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:
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));
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.