Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

string - Change format of DateTime object in c# and store back as DateTime object

I want to convert string 2017-03-05 to Datetime object in c# in format yyyy-MM-dd

string startDate = "2017-03-05"; 
DateTime myDate = DateTime.ParseExact(startDate, "yyyy-MM-dd",
                         System.Globalization.CultureInfo.InvariantCulture);

myDate gives me 05-03-2017 00:00:00

But I want myDate DateTime object like 2017-03-05 00:00:00 i.e yyyy-MM-dd format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you parse your string to DateTime, it will have no format.

DateTime structure does not have any implicit format. It just have date and time values which is based on long field as Ticks. Format concept only applies when you try to get it's textual (aka string) representation of it. It is really important to understand the difference between a DateTime instance and it's formatted string representation.

So, if you wanna get a specific textual format of your DateTime, you will need to get it's string representation again.

string result = myDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...