Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Convert Date from 6/05/2020 format to dd/MM/YYYY format

I am facing a small issue which i am not able after trying so many things so here it goes ..... There is a text box in my page in which i am entering date and i want that date in a datetime object.

for ex : date entd : 6 05 2020(dd/MM/yyyy) should be in same format when i am accessing it in date time object but it is getting changed to (6.05.2020ie: MM/dd/yyyy format).

i hope i am making sense here all i want is some thing like this.....

DateTime dt = convert.ToDateTime(txtDate.Text);

dt should be (11/2/2010 rather then 2/11/2010)

@oded after using the following code

DateTime sDate, eDate = new DateTime(); 

//To modify dates for our use. DateTime.TryParseExact(txtFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out sDate);

DateTime.TryParseExact(txtFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out eDate); 

What i am getting in edate and sdate is 6 05 2020 12:00:00 AM where it should be 6/05/2020

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

DateTime doesn't store dates in any specific format - it uses an internal representation (what exactly shouldn't matter).

After parsing the string to a DateTime, there is no inherent format there. There is only a format when you output the value. What you see in the debugger is simply a conversion to a string using your system settings.

If you want to format the DateTime, use ToString with a format string:

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

The converse also applies - if you need to parse the string unambiguously, use ParseExact or TryParseExact (both static members of of DateTime):

DateTime dt;

if(DateTime.TryParseExact(txtDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out td))
{
  // Valid date used in `txtDate.Text`, use dt now.
}

Read about custom and standard Date and Time format strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...