如何将Date对象格式化为字符串?


当前回答

两个纯JavaScript单行程序

在这个答案中,我发展了JD Smith的想法。我能够缩短JD-Smith正则表达式。

let format=d=>d.toString().replace(/\w+(\w+)(\d+)(\d+).*/,'$2-$1-$3');console.log(格式(Date()));

Dave的也是基于JD Smith的想法,但他避免了正则表达式,并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改拆分参数),并在包装器中使其不透明。

let format=(d,a=d.toString().split``)=>a[2]+“-”+a[1]+“-“+a[3];console.log(格式(Date()));

其他回答

对于任何想要复制、粘贴和采用真正简单的ES6解决方案的人来说:

const dateToString=d=>`${d.getFullYear()}-${('00'+(d.getMonth()+1)).slice(-2)}-${('0'+d.getDate()).spice(-2)}`//如何使用:const myDate=新日期(Date.parse('04 Dec 1995 00:12:00 GMT'))console.log(dateToString(myDate))//1995-12-04

要获得“2010年8月10日”,请尝试:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

有关浏览器支持,请参阅toLocaleDateString。

这可能有助于解决问题:

var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));

该函数的灵感来自Java的SimpleDateFormat。它提供各种格式,例如:

dd-MMM-yyyy → 17-Jul-2018
yyyyMMdd'T'HHmmssXX → 20180717T120856+0900
yyyy-MM-dd'T'HH:mm:ssXXX → 2018-07-17T12:08:56+09:00
E, dd MMM yyyy HH:mm:ss Z → Tue, 17 Jul 2018 12:08:56 +0900
yyyy.MM.dd 'at' hh:mm:ss Z → 2018.07.17 at 12:08:56 +0900
EEE, MMM d, ''yy → Tue, Jul 17, '18
h:mm a → 12:08 PM
hh 'o''''clock' a, X → 12 o'clock PM, +09

代码示例:

函数formatWith(formatStr,date,opts){if(!date){date=新日期();}opts=opts||{};let _days=opts.days;如果(!_days){_days=[星期日、星期一、星期二、星期三、星期四、星期五、星期六];}let _months=opts.months;如果(!_months){_months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];}常量pad=(number,strDigits,isUnpad)=>{const strNum=number.toString();如果(!isUnpad&&strNum.length>strDigits.length){返回strNum;}其他{return('0000'+strNum).sslice(-strDigits.length);}};常量时区=(日期,字母)=>{常量块=[];const offset=-date.getTimezoneOffset();chunk.push(偏移量==0?“Z”:偏移量>0?“+”:“-”)//添加Z或+-如果(偏移量==0)返回块;chunk.push(pad(数学地板(偏移量/60),“00”))//小时if(letter==“X”)返回chunk.join(“”);if(letter=='XXX')chunk.push(':');chunk.push(pad((偏移量%60),'00'))//最小值return chunk.join(“”);};const ESCAPE_DELIM=“\0”;常量escapeStack=[];const escapedFmtStr=格式Str.替换(/'.*?'/g,m=>{escapeStack.push(m.replace(/'/g,''));return ESCAPE_DELIM+(escapeStack.length-1)+ESCAPE_DELIM;});常量格式化Str=转义FmtStr.replace(/y{4}| y{2}/g,m=>pad(date.getFullYear(),m,true)).replace(/M{3}/g,M=>_months[date.getMonth()]).replace(/M{1,2}/g,M=>pad(date.getMonth()+1,M)).replace(/M{1,2}/g,M=>pad(date.getMonth()+1,M)).replace(/d{1,2}/g,m=>pad(date.getDate(),m)).replace(/H{1,2}/g,m=>pad(date.getHours(),m)).替换(/h{1,2}/g,m=>{const hours=date.getHours();返回垫(小时==0?12:小时>12?小时-12:小时,m);}).replace(/a{1,2}/g,m=>date.getHours()>=12?'下午:上午).replace(/m{1,2}/g,m=>pad(date.getMinutes(),m)).replace(/s{1,2}/g,m=>pad(date.getSeconds(),m)).replace(/S{3}/g,m=>pad(date.getMilliseconds(),m)).replace(/[E]+/g,m=>_days[date.getDay()]).替换(/[Z]+/g,m=>时区(日期,m)).替换(/X{1,3}/g,m=>时区(日期,m));const unescapedStr=格式化Str.替换(/\0\d+\0/g,m=>{const unescaped=escapeStack.shift();返回unscaped.length>0?未转义:“\”;});返回unscapedStr;}//让我们用上面的函数格式化const dateStr='2018/07/17 12:08:56';const date=新日期(dateStr);常量模式=[“年-月-日”,“yyyyMMdd''HHmmssXX”,//ISO8601“yyyy-MM-dd''HH:MM:ssXXX”,//ISO8601EX“E,dd MMM yyyy HH:mm:ss Z”,//RFC1123(RFC822)类似电子邮件“yyyy.MM.dd'at'hh:MM:ss Z”,//hh显示1-12“EEE,MMM d,'yy”,“h:mm a”,“hh'o'''时钟'a,X”,];for(let模式){console.log(`${pattern}→ ${formatWith(pattern,date)}`);}

你可以把它当作图书馆

它也作为NPM模块发布。您可以在Node.js上使用它,也可以在浏览器的CDN中使用它。

节点.js

const {SimpleDateFormat} = require('@riversun/simple-date-format');

在浏览器中

<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format@1.0.2/dist/simple-date-format.js"></script>

按照以下步骤编写代码。

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

GitHub上的源代码:

https://github.com/riversun/simple-date-format

它在InternetExplorer11、Firefox和Chrome中的工作方式相同(当选择en-UK时,Chrome80.x显示12小时格式)。

const d=新日期('2010/08/05 23:45')//26.3.2020const dtfUK=新Intl.DateTimeFormat('UK',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//const dtfUS=新Intl.DateTimeFormat('en',{年:'数字',月:'2位数',日:'2位',小时:'2-位数',分钟:'2-位',秒:'2-数位'})//console.log(dtfUS.format(d));//2010年5月8日下午11:45:00console.log(dtfUK.format(d));//05.08.2010 23:45:00/*node.js:2010年5月8日,晚上11:45:002010-08-05 23:45:00*/

有什么更一般的吗?

var d=新日期('2010-08-10T10:34:56.789Z');var str=d.toDateString()+/-2010年8月10日星期二“”+d.toTimeString().split(“”)[0]+/-12:34:56,GMT+0x0(GMT+00:00)“”+(d.getMonth()+101)+/-108“”+d.获取毫秒();//789console.log(str);//2010年8月10日星期二12:34:56 108 789console.log(//$1周二$2 8月$3 11$4 2020$5 12$6 34$7 56$8 108$9 789str.replace(/(\S{3})(\S}3)(\d{1,2})); // 2010年8月10日12:34.789(星期二)/*$1:星期二工作日字符串$2:8月短文本$3:11天$4:2010年$5:12小时$6:34分钟$7:56秒$8:08个月$9:789毫秒*/

或例如1行IIFE“库”;-)

控制台日志((函数(frm,d){return[d.toDateString(),d.toTimeString().split(“”)[0],(d.getMonth()+101),d.getMilliseconds()].jjoin(“).replace(/(\S{3})(\S})('$4/$8/$3$5:$6($1)',新日期()));

如果不需要,可以删除无用的部件和/或更改索引。