【发布时间】:2019-01-25 21:58:51
【问题描述】:
我有这段代码,当单击按钮时,它会返回当前时间。但是,它以一种非常难以理解的格式返回时间。如何格式化以使其看起来更好?
using System;
using Microsoft.AspNetCore.Mvc;
using Clockwork.API.Models;
namespace Clockwork.API.Controllers
{
[Route("api/[controller]")]
public class CurrentTimeController : Controller
{
// GET api/currenttime
[HttpGet]
public IActionResult Get()
{
var utcTime = DateTime.UtcNow;
var serverTime = DateTime.Now;
var ip = this.HttpContext.Connection.RemoteIpAddress.ToString();
var returnVal = new CurrentTimeQuery
{
UTCTime = utcTime,
ClientIp = ip,
Time = serverTime
};
using (var db = new ClockworkContext())
{
db.CurrentTimeQueries.Add(returnVal);
var count = db.SaveChanges();
Console.WriteLine("{0} records saved to database", count);
Console.WriteLine();
foreach (var CurrentTimeQuery in db.CurrentTimeQueries)
{
Console.WriteLine(" - {0}", CurrentTimeQuery.UTCTime);
}
}
return Ok(returnVal);
}
}
}
返回如下:
{"currentTimeQueryId":15,"time":"2018-08-19T11:44:54.3348267-04:00","clientIp":"127.0.0.1","utcTime":"2018-08-19T15:44:54.3348267Z"}
【问题讨论】:
-
{0:dd MMM yyyy HH:mm:ss}是众多格式化选项之一... -
您希望它采用什么特定格式?您通常使用某种格式的
DateTime.ToString -
@CamiloTerevinto:如果您将其展示给用户,那当然可以。如果您尝试创建像 JSON 这样的机器可读格式,那么 ISO-8601 几乎总是最合适的格式。
-
@DaisyShipton 好吧,“看起来更好”对我来说听起来不像是机器可读的格式:)
-
@CamiloTerevinto:但输出是 JSON。这不是设计为人类可读的。如果目标是向人类显示数据,那么 JSON 不是用于该目的的最佳格式。基本上,OP 需要决定一种方式或另一种方式:人类消费(不是 JSON,可能对文化敏感)或机器消费(JSON,对文化不敏感)。
标签: c# asp.net-core