将字符串转换为DateTime? [英] Converting String to DateTime?
本文介绍了将字符串转换为DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我想将字符串转换为日期时间。
字符串为'17 / 03/2001'。这是'dd / MM / yyyy'格式。
我的系统日期时间格式为'MM / dd / yyyy'格式
我尝试转换为
Hi All,
I want to convert a string to datetime.
the string is '17/03/2001'. this is in 'dd/MM/yyyy' format.
my system datetime format is 'MM/dd/yyyy' format
I tried converting like
Convert.ToDateTime("17/03/2001")
。现在它收到了错误。
但是当我将系统日期格式更改为'dd / MM / yyyy'时,转换工作正常。
无论系统日期如何,我都需要将日期转换为特定格式。因为我在网络应用程序中工作。
任何人请帮助我。
. Now it catches error.
But when I change my system date format to 'dd/MM/yyyy' conversion works fine.
I need to convert date to a specific format irrespective of system date. Since I am working in a web application.
any one please help me.
推荐答案
DateTime.ParseExact("17/03/2001", "dd/MM/yyyy", CultureInfo.InvariantCulture);
using System.Globalization;
txtDate.Text = "17/03/2001";
DateTime From = DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
参考: CultureInfo.InvariantCulture Property
使用自定义类进行与DateTime相关的工作>
Use A Custom Class for DateTime related work
public static class Timechanger{
public static DateTime StringToDate(string strDt, char[] separator)
{
string[] dateparts1 = strDt.Split(separator);
var sdate = new DateTime(Convert.ToInt32(dateparts1[2]), Convert.ToInt32(dateparts1[1]),
Convert.ToInt32(dateparts1[0]));
return sdate;
}
public static DateTime StringToDate(string strDt)
{
return StringToDate(strDt, new[] {'-', '/'});
}
public static string DateToString(DateTime dt)
{
string strDt = Convert.ToString(dt.Day) + "/" + Convert.ToString(dt.Month) + "/" + Convert.ToString(dt.Year);
return strDt;
}
}
这篇关于将字符串转换为DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文