项目中总会遇到对时间的处理,格式问题 还有UTC时间和LOCAL时间显示出错。
- 如何设置全局的时间toString的格式,从一个是dataTime类型的时间转成我们想要的格式:
C#中最简单的就是直接用DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 做,当然可以但都要写这样的格式有些麻烦,我们可以设置全局的时间toString的格式,重写datetime中的一些方法来实现我们自己要的格式。
- 首先到global.cs文件下面 在应用启动的时候,去加载时间格式初始化,这里重写了Application_BeginRequest 方法。
这里是setCultureAndDateTiemFormat 方法, 重写shortDate(),这些方法。 时间格式是配置在config中的。protected void Application_BeginRequest(object sender, EventArgs e) { LocalizationSetting.SetCultureAndDateTimeFormat(); }
<add key="shortTimeFormat" value="HH:mm:ss" /> <add key="shortDateFormat" value="dd/MM/yyyy" />
然后,就可以在代码中这样用了public static void SetCultureAndDateTimeFormat() { var globalizationSection = GlobalizationSectionFactory.GetGlobalizationSection(); var culture = new CultureInfo(globalizationSection.Culture); var shortDateFormat = SysParamFactory.GetSysParam<string>("shortDateFormat"); var shortTimeFormat = SysParamFactory.GetSysParam<string>("shortTimeFormat"); if (!string.IsNullOrWhiteSpace(shortDateFormat) && !string.IsNullOrWhiteSpace(shortTimeFormat)) { culture.DateTimeFormat.ShortDatePattern = shortDateFormat; culture.DateTimeFormat.LongDatePattern = shortDateFormat; culture.DateTimeFormat.ShortTimePattern = shortTimeFormat; culture.DateTimeFormat.LongTimePattern = shortTimeFormat; culture.DateTimeFormat.FullDateTimePattern = string.Format("{0} {1}", shortDateFormat, shortTimeFormat); } CultureInfo.DefaultThreadCurrentCulture = culture; CultureInfo.DefaultThreadCurrentUICulture = culture; Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; }
最近项目返现,从前端传过来的时间是正确的,但是在拿到之后,因为ajax请求的这边用到了Newtonsoft.Json 这个第三方开源的类库,但是发现这个时间转成object是用UTC的时间,所以一定要记得用ToLocalTime()再去转一下才正确。StartDate.ToLocalTime().ToShortDateString()
Newtonsoft.Json.JsonConvert.DeserializeObject<ARequestModel>(Request.Form["absenceRequestModel"]);
- 字符转成时间:c#中默认DateTime.Parse(satrtDate); 使用这个方法,日期格式必须是‘yyyy-MM-dd HH:mm:ss’这样的格式,如果我们‘dd/MM/yyyy’有这样的格式就要指定格式来转换了.
var newData = DateTime.ParseExact(satrtDate, "dd/MM/yyyy",null);
- 有时候对接接口时发现,有些时间数据格式是这个样子的,其实也是json中的一种,"\/Date(1506788352175+0800)\/" 。
但是我发现我用Newtonsoft.Json 去把object转成来的默认时间格式这个样子"2017-10-01T00:19:12.1757748+08:00"。
最终网上找了下,我用了下面C#自带的DataContractJsonSerializer 可以成功转成上面的格式。
public static string EntityToJson(object requestEntity)
{
var serializer = new DataContractJsonSerializer(requestEntity.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, requestEntity);
byte[] myByte = new byte[ms.Length];
ms.Position = 0;
ms.Read(myByte, 0, (int)ms.Length);
string dataString = Encoding.UTF8.GetString(myByte);
ms.Close();
return dataString;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}