废话不多说,先看一段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DateTime dateTime = DateTime.Now;
Console.WriteLine(JsonConvert.SerializeObject(dateTime));
Console.ReadKey();
}
}
}
代码很简单,就是获取当前时间,然后序列化成JSON字符串,得到的结果如下:
"2020-01-03T11:09:51.3122483+08:00"
很明显这不是我们想要的结果,如果想获取标准格式化的时间,请看下面这段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DateTime dateTime = DateTime.Now;
Console.WriteLine(GetTimeString(dateTime));
Console.ReadKey();
}
static string GetTimeString(DateTime dateTime)
{
IsoDateTimeConverter converter = new IsoDateTimeConverter();
converter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
return JsonConvert.SerializeObject(dateTime, Formatting.Indented, converter);
}
}
}
结果如下:
"2020-01-03 11:11:41"