如何更改字符串到日期格式 [英] How to change string to date format
本文介绍了如何更改字符串到日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将字符串更改为日期格式c#
即2 / 22/2014 5:08:46 PM到2014-02-22。
谢谢
GSS
解决方案
1。首先,使用tryparse检查日期字符串是否有效;
2.指定所需的日期格式;
3.然后可以进行转换。
使用系统;
public class 计划
{
public static void Main()
{
// 更改2/22/2014 5:08:46 PM至2014-02-22。
string dateString = 2/22/2014 5:08:46 PM;
Console.WriteLine( 原始字符串为{0}, dateString);
DateTime dt;
if (DateTime.TryParse(dateString, out dt))
{
string format = yyyy -MM-DD跨度>;
Console.WriteLine(dt.ToString(format));
}
else
{
Console.WriteLine( 不是有效的日期时间);
}
}
}
// String to DateTime
String MyString;
MyString = 2/22/2014 5:08:46 PM;
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, yyyy-MM-dd HH:mm , null );
在CodeProject上找到一篇非常好的文章,简单字符串到日期时间,日期时间到字符串和格式 [ ^ ]和是的, MSDN [ ^ ]。
-KR
// 最后,我清除了我的解决方案。
string recDate = 2/22/2014 5:08:46 PM;
DateTime dr = Convert.ToDateTime(recDate);
object s = String .Format( {0:u},dr);
Hi,
I need to change the string to Date format in c#
i.e 2/22/2014 5:08:46 PM to 2014-02-22.
Thanks
GSS
解决方案
1. First, check that the date string is a valid one using tryparse;
2. Specify the desired date format;
3. then can do the conversion.
using System; public class Program { public static void Main() { // change 2/22/2014 5:08:46 PM to 2014-02-22. string dateString = "2/22/2014 5:08:46 PM"; Console.WriteLine("The original string is {0}", dateString); DateTime dt; if (DateTime.TryParse(dateString, out dt)) { string format = "yyyy-MM-dd"; Console.WriteLine(dt.ToString(format)); } else { Console.WriteLine("Not a valid datetime"); } } }
// String to DateTime String MyString; MyString = "2/22/2014 5:08:46 PM"; DateTime MyDateTime; MyDateTime = new DateTime(); MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm", null);
A very good article found on CodeProject, Easy String to DateTime, DateTime to String and Formatting[^] and yes, MSDN[^] as well.
-KR
//Finally, I cleared my solution. string recDate = "2/22/2014 5:08:46 PM"; DateTime dr = Convert.ToDateTime(recDate); object s = String.Format("{0:u}", dr);
这篇关于如何更改字符串到日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文