如何将字符串转换为给定格式的日期 [英] How to convert string to date in a given format
本文介绍了如何将字符串转换为给定格式的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将"29-04-2012"转换为以下格式"2012年4月29日"
我正在使用以下代码
How do I convert ''29-04-2012'' in following format ''29-Apr-2012''
I am using following code
String.Format("{0:DD,MMM,YYYY}",date)
但它不起作用
[edit]已删除呼喊声-OriginalGriff [/edit]
but its not working
[edit]SHOUTING removed - OriginalGriff[/edit]
推荐答案
将其转换为DateTime,然后返回到字符串:
Convert it to a DateTime and then back to a string:
DateTime dt = DateTime.ParseExact("29-04-2012", "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = dt.ToString("dd.MMMM.yyyy");
尝试始终将日期保持为DateTime格式而不是字符串-尽早从字符串转换,并尽可能晚地转换回字符串.大多数系统都可以使用DateTime,而不会因用户输入日期格式而感到困惑!
Try to always keep dates in DateTime format rather than string - convert from string as early as possible, and convert back to string as late as possible. Most systems will work with a DateTime without getting confused by the date format the user entered it in!
尝试以下操作:
Try this:
DateTime date = DateTime.ParseExact("29-04-2012", "dd-MM-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
这篇关于如何将字符串转换为给定格式的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文