DateTime.Parse American Date Format C#
Probably a simple question -
I'm reading in data from a number of files.
My problem is, that when I'm reading in the date from an american file, I parse it like so:
DateSold = DateTime.Parse(t.Date)
This parses the string t.Date into a date format, however it formats the american date to a europea开发者_运维问答n date, e.g.
If the date is in the file as 03/01/2011, it is read as the 3rd of January, 2011, when it should be the 1st of March 2011.
Is there a way of doing this so that it formats to the european date?
var dt = DateTime.ParseExact(t.Date, "MM/dd/yyyy", CultureInfo.InvariantCulture);
The DateTime itself has no formatting, it is only when you convert it to or from a string that the format is relevant.
To view your date with American format, you pass the format to the ToString method
string americanFormat = dt.ToString("MM/dd/yyyy");
If you are parsing the date from a file which is specifically a US formatted file then simply pass the US culture information into the parse function as follows;
var usCulture = "en-US";
var dateValue = DateTime.Parse(dateString, new CultureInfo(usCulture, false));
This way you can simply swap out the culture string per different region required for parsing. Also, you no longer have to research the specific datetime format nuances for each culture as .Net will take care of this for you as designed.
Use DateTime.ParseExact
or DateTime.TryParseExact
when parsing, and specify a format string when you format with ToString
too.
Note that there's no such thing as "an American date" after it's been parsed. The DateTime
value has no concept of formatting.
It sounds like you're not actually interested in the Parse
part so much as the formatting part, e.g.
string formatted = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
... but I would recommend that you control both the parsing and formatting explicitly.
If you have different file formats, you'll need to give different format strings when you read each file. How you then format the data is a separate decision.
If you know the format ahead of time, you can use DateTime.ParseExact, using the American format as your format string.
string formatteddate=DateTime.Now.ToString("d") // output: 11/8/2012
string formatteddate=DateTime.Now.ToString("D") // output: Monday, November 08, 2012
string formatteddate=DateTime.Now.ToString("f") // output: Monday, November 08, 2012 3:39 PM
string formatteddate=DateTime.Now.ToString("g") // output: Monday, November 08, 2012 3:39:46 PM
string formatteddate=DateTime.Now.ToString("d") // output: 11/8/2012 3:39 PM
More date-time format in asp.net is given here.
http://dateformat.blogspot.in/2012/09/date-time-format-in-c-aspnet.html
精彩评论