var time=new Date(parseInt(1420184730) * 1000).toLocaleString();
这样的转换出来的时间戳一般都会有具体时间跟在后面的。如果我只想要前面的日期,后面的时间都不要,用过.substr(0,11),但这个方法太死了,不能灵活的去截取。请问有没有更加好的实现方法?
.substr(0,11)
拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...
Date对象有toLocaleDateString方法可以只返回日期啊,这样不行么:
var time=new Date(parseInt(1420184730) * 1000).toLocaleDateString()
javascripttime.split(',')[0]; // 2015/1/2 may differ with different system language
javascript
time.split(',')[0]; // 2015/1/2 may differ with different system language
or
var date = new Date(parseInt(1420184730) * 1000); [date.getFullYear(), date.getMonth()+1, date.getDate()].join('/'); // 2015/1/2
new Intl.DateTimeFormat('zh-cn').format(date); // 2015/1/2
参照这个文档,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob... 我发现toLocalString方法返回的字符串格式规律不是那么明显。 如果题主的场景是一般2015/1/2这种格式的,我觉得可以用正则表达式:
toLocalString
2015/1/2
var time=new Date(parseInt(1420184730) * 1000).toLocaleString(); var matches = time.match(/^[^\s]*/); console.log(matches[0]); // 2015/1/2
如果是其他格式的就。。。,我觉得最保险的做法是@bf同学提出的第二种做法。
所以你想要的是灵活的,而不是固定格式的是吧?那下面这个非常灵活,只要在使用.format方法前注册好下面的方法就可以用了
.format
用法:
var time=new Date(parseInt(1420184730) * 1000).format('yyyy年M月d日'); console.log(time);//输出:"2015年1月2日"
用之前记得先注册:
/** * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * 例子: * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 * (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 * @param fmt string * @return string * */ 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; }
new Date(parseInt(1420184730) * 1000).toJSON().slice(0,10)//2015-01-02
new Date(parseInt(1420184730) * 1000).toJSON().slice(0,10)
new Date(parseInt(1420184730) * 1000).toISOString().slice(0,10);
Date对象有toLocaleDateString方法可以只返回日期啊,这样不行么:
or
or
参照这个文档,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob...
我发现
toLocalString
方法返回的字符串格式规律不是那么明显。如果题主的场景是一般
2015/1/2
这种格式的,我觉得可以用正则表达式:如果是其他格式的就。。。,我觉得最保险的做法是@bf同学提出的第二种做法。
所以你想要的是灵活的,而不是固定格式的是吧?那下面这个非常灵活,只要在使用
.format
方法前注册好下面的方法就可以用了用法:
用之前记得先注册:
new Date(parseInt(1420184730) * 1000).toJSON().slice(0,10)
//2015-01-02new Date(parseInt(1420184730) * 1000).toISOString().slice(0,10);