前后台格式化时间戳

众所周知,数据库中的时间和我们在网页上所需要展示的时间看起来没有什么不同,可实际上它在转换的过程中演变为时间戳,简单来讲呢就是从北京时间1970年01月01日08时00分00秒)起至现在的总秒数,怎么说也有十位数了吧,并不是我们想要的年-月-日格式,于是呢,就有了下面的代码

//时间戳转为C#格式时间  
 public static DateTime ConvertStringToDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
//输出接口
public ActionResult Search(Entity model)
{
	JsonSerializerSettings setting = new JsonSerializerSettings();
	setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
	setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
	var jsonStr =JsonConvert.SerializeObject(obj,setting);
	return Content(jsonStr, "application/json");
}

这里使用了Newtonsoft.Json 序列化包,直接在项目中右键菜单管理NuGet程序包添加引用即可
Content是直接输出对象的格式,也可以使用json函数返回json数据,不过要注意一点,如果json数据量过大会报错,这时候需要重写Json函数,由于篇幅有限,下一篇我会讲

也可以直接用js函数进行时间戳的格式化

this.FormatterDate = function (value, format) {
        if (!format)
            format = 'yyyy-MM-dd hh:mm:ss';
        if (!value)
            return "";
        return eval('new ' + eval(value).source).format(format);
    }
//日期格式化扩展
Date.prototype.Format = function (fmt) { //author: meizz   
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日   
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

如何使用我就不作赘述了,有不明白的地方欢迎在下方评论区留言

猜你喜欢

转载自blog.csdn.net/cslx5zx5/article/details/91382447