首页 > 解决方案 > 在 C# 中更改长日期格式

问题描述

我在 xtraReport 上使用 devexpress 17.2 dateedit 组件作为参数。如何格式化我在控制器中作为参数值获取的日期,例如“2019 年 7 月 15 日星期一 00:00:00 GMT +0300(东非时间)?

控制器

String sDate = Request. Param[" startdate"].ToString();
DateTime startDate = Convert.ToDateTime(startdate);

它抛出一个错误

“字符串未被识别为有效的日期时间”。

标签: c#devexpress

解决方案


您可以使用 DateTime.TryParseExact 并使用要转换的格式。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = "Mon Jul 15 2019 00:00:00 GMT +0300 ";
                DateTime t;
                DateTime.TryParseExact(s,
                       "ddd MMM dd yyyy h:mm:ss GMT +0300 ",
                       CultureInfo.InvariantCulture,
                       DateTimeStyles.None,
                       out t);
            }
            catch(Exception ex)
            {
                //Log exception
            }

        }
    }
}

推荐阅读