我想将日期转换为DD/MM/YYYY/HH:MM:SS
格式。日期由用户提供。
我正在使用以下代码:
string fromdate = context.Request.QueryString["fromdate"];
string todate = context.Request.QueryString["todatedate"];
DateTime fromDaten = DateTime.MinValue;
DateTime toDaten = DateTime.MinValue;
try
{
fromDaten = FormatDate(fromdate + " 00:00:00");
toDaten = FormatDate(todate + " 00:00:00");
}
catch (Exception ex) { }
我想将fromdate
和todate
转换为DD/MM/YYYY/HH:MM:SS
格式。当我尝试这样做时,我得到01/01/0001/00:00:00
。
我有以下代码:
try
{
string dateTimeString = todate;
dateTimeString = Regex.Replace(dateTimeString, @"[^\u0000-\u007F]", string.Empty);
string inputFormat = "yyyy-MM-dd HH:mm:ss";
string outputFormat = "dd-MM-yyyy HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);
return Convert.ToDateTime(output);
}
catch (Exception ex)
{
throw;
}
答案 0 :(得分:1)
你应该使用TryParse/TryParseExact
代替try / catch,这是更昂贵而不是best practice。
string fromDate = "2016/10/20/12:13:14";
DateTime fromDaten = DateTime.MinValue;
bool fromParsed = DateTime.TryParseExact(fromDate, "yyyy/MM/dd/HH:mm:ss",
new System.Globalization.CultureInfo("en-US"),
System.Globalization.DateTimeStyles.None, out fromDaten);
// you may check fromParsed and handle invalid date/time
我仅为fromDate
提供了示例。您可以创建一个解析函数来处理所有日期字符串。
答案 1 :(得分:0)
那段代码有点乱,试试这个:
string fromdate = context.Request.QueryString["fromdate"];
string todate = context.Request.QueryString["todatedate"];
DateTime fromDaten = DateTime.Parse(String.Join("/", fromdate.Split("/".ToCharArray()).Reverse().ToArray()));
DateTime toDaten = DateTime.Parse(String.Join("/", fromdate.Split("/".ToCharArray()).Reverse().ToArray()));
答案 2 :(得分:0)
试试这个 -
string fromdate = context.Request.QueryString["fromdate"];
string todate = context.Request.QueryString["todatedate"];
if(!string.IsNullOrEmpty(fromdate)||!string.IsNullOrEmpty(todate)) /* check query string value */
{
DateTime from=Convert.ToDateTime(fromdate);
DateTime to=Convert.ToDateTime(todate);
try
{
fromDate=from.ToString("dd/MM/YYYY HH:mm:ss");/*Here you get date time in required format */
toDate = to.ToString("dd/MM/YYYY HH:mm:ss");
}
catch (Exception ex)
{
}
}
答案 3 :(得分:0)
尝试以下
DateTime dt = DateTime.ParseExact(sDate, "MM/dd/yyyy",CultureInfo.InvariantCulture);
让我知道这是否有效..