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


当前回答

这可以帮助:

export const formatDateToString = date => {
    if (!date) {
        return date;
    }
    try {
        return format(parse(date, 'yyyy-MM-dd', new Date()), 'dd/MM/yyyy');
    } catch (error) {
        return 'invalid date';
    }
};

其他回答

字符串转换


// date 
const dateConvert = {
  dasher: dt => {
    let m = (dt.getMonth() + 1) === 13 ? 1 : (dt.getMonth() + 1);
    m = m < 10 ? `0${m}` : m.toString();
    let d = dt.getDate();
    d = d < 10 ? `0${d}` : d.toString();
    return `${dt.getFullYear()}-${m}-${d}`;
  }, 
  slasher: dt => {
    return dateConvert.slash(dateConvert.dasher(dt));
  }, 
  dash: str => {
    // 03/11/2022 -> 2022-03-11
    let [d, m, y] = str.split('/');
    return `${y}-${m}-${d}`;
  }, 
  slash: str => {
    // 2022-03-11 -> 03/11/2022
    let [y, m, d] = str.split('-');
    return `${d}/${m}/${y}`
  }
}

// console.log(dateConvert.dasher(new Date('01/31/2001')));

它在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)',新日期()));

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

Use:

thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();

这采用JSON日期“/date(1429573751663)/”,并生成格式化字符串:

"4/21/2015"

大家好,我有一个代码,用于为日期添加日期和格式。

 const FechaMaxima = new Date();
 FechaMaxima.setDate(FechaMaxima.getDate() + 6);
 FechaMaxima.toISOString().substring(0, 10);

我们有很多解决方案,但我认为最好的是Moment.js。所以我个人建议将Moment.jss用于日期和时间操作。

console.log(moment().format('DD-MMM-YYYY'));<script src=“//cdnjs.cloudflare.com/ajax/libs/ment.js/2.14.1/moment.min.js”></script>