开发者

Formatting string to string Date Format .net 2.0

Given a string value eg "03252013" I need to convert this string to be in this format "DDMMYYYY". Which function do you use? The result should be "25032013"

string myTestDate="03252013";
string resultDat开发者_运维问答e=??

Thanks


Use DateTime.ParseExact method. Then use ToString to convert to appropriate format.

var dt = DateTime.ParseExact("03252013", "MMddyyyy", CultureInfo.InvariantCulture);
var result = dt.ToString("ddMMyyyy"); //25032013


string resultDate = DateTime.ParseExact(myTestDate, "MMddyyyy", CultureInfo.InvariantCulture).ToString("ddMMyyyy");


Simply parse then re-format:

string input = "03252013"
DateTime date = DateTime.ParseExact(input, "MMddyyyy", CultureInfo.InvariantCulture);
string resultDate = date.ToString("ddMMyyyy");


If your needs really are that simple I would consider just switching the values around...

string input = "03252013";
string output = input.Substring(2, 2) + input.Substring(0, 2) + input.Substring(4, 4);

...dont forget to validate the input before using substring (checking the length is 8 will probably be enough)

NOTE: If it is likely that your input or output formats will change then it would be more ideal to do the DateTime.Parse technique as suggested by many others. But if this is really the only situations then this method should provide better performance... slightly ;)


You, can use the Help of following code part to convert.

string resultDate = DateTime.ParseExact(myTestDate, "MMDDYYYY", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None).ToString("DDMMYYYY");


Use this: resultDate = DateTime.Parse(myTestDate,"d").toString(); "d" is a format provider that says to farmat the date like this: DD/MM/YYYY

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜