前台显示数据时,经常遇到的DateTime转换问题,推荐给大家一个小工具:

eg: dateTime.js

var DateUtil={
	dateToStr:function(formatStr,date){
		date = DateUtil.stringToDate(date);
		if(typeof arguments[0]=='undefined'){
				formatStr="yyyy-MM-dd HH:mm:ss";
				date=new Date();
		}else{
			if(typeof arguments[0]=='string'){
				formatStr=arguments[0];
			}else{
				formatStr="yyyy-MM-dd HH:mm:ss";
				date=arguments[0];
			}
		}
        if(typeof arguments[1]=='undefined'){
			date=new Date();
		}else{
			if(typeof arguments[1]=='string'){
				formatStr=arguments[1];}
			else{
				date=arguments[1];
			}
		}
        var str=formatStr;
        var Week=['日','一','二','三','四','五','六'];
        str=str.replace(/yyyy|YYYY/,date.getFullYear());
        str=str.replace(/yy|YY/,(date.getYear()%100)>9?(date.getYear()%100).toString():'0'+(date.getYear()%100));
        str=str.replace(/MM/,date.getMonth()>9?(date.getMonth()+1):'0'+(date.getMonth()+1));
        str=str.replace(/M/g,date.getMonth());str=str.replace(/w|W/g,Week[date.getDay()]);
        str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0'+date.getDate());
        str=str.replace(/d|D/g,date.getDate());
        str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0'+date.getHours());
        str=str.replace(/h|H/g,date.getHours());
        str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0'+date.getMinutes());
        str=str.replace(/m/g,date.getMinutes());
        str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0'+date.getSeconds());
        str=str.replace(/s|S/g,date.getSeconds());
        return str;
    },
    stringToDate: function (fDate) {//字符串转换DateTime
        var fullDate = fDate.split(" ")[0].split("-");
        var fullTime = fDate.split(" ")[1].split(":");

        return new Date(fullDate[0], fullDate[1] - 1, fullDate[2], (fullTime[0] != null ? fullTime[0] : 0), (fullTime[1] != null ? fullTime[1] : 0), (fullTime[2] != null ? fullTime[2] : 0));
    }
 };

instanc:

<script type="text/javscript">
    var dateStr='2019-03-11 11:12:36';
    var formatDate=DateUtil.dateToStr("yyyy-MM-dd HH:mm:ss", dateStr);
    consloe.info(formatDate);
</script>

遇到困难时不要抱怨,既然改变不了过去,那么就努力改变未来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值