代码之家  ›  专栏  ›  技术社区  ›  Ramdhas

DIV标记内的日期格式化程序

  •  0
  • Ramdhas  · 技术社区  · 3 年前
         <div>
            <strong>Date: </strong>
            ${dateInUtc}
         </div>
    

    (2021 12-09T15:43:29+01:00) 包含UTC格式的日期。 需要这样格式化 .

    如何在不使用外部库的情况下实现这一点?

    1 回复  |  直到 3 年前
        1
  •  1
  •   phuzi    3 年前

    因为所需的格式接近于您已经拥有的格式,所以您可以非常简单地执行此操作,而不必首先解析日期。

    const dateInUtc = `2021-12-09T15:43:29+01:00`;
    
    const formattedDate = dateInUtc.replace(`T`, ` - `).split(`+`)[0];
    
    console.log(formattedDate);
        2
  •  0
  •   ArtBindu    3 年前

    如果您正在使用任何框架,那么请在该框架中使用数据管道。

    例子: Datepipe-Angular

    如果未使用任何框架,请使用日期格式实用程序函数,如:

    df = (function(d) {
        d = new Date(d);
        return `${d.getFullYear()}-${(d.getMonth()+1).toString().replace(/^[0-9]$/g, '0$&')}-${(d.getDate()).toString().replace(/^[0-9]$/g, '0$&')} - ${(d.getHours()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getMinutes()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getSeconds()).toString().replace(/^[0-9]$/g, '0$&')}`;
    });
    console.log(df(new Date().toUTCString()));
    

    输出:

    '2022-07-22 - 14:41:36'
    

    说明: 这是从日期对象获取数据的目标。

        d = new Date(d);
        obj = {
            date: d.getDate(),
            month: d.getMonth(),
            year: d.getFullYear(),
            hour: d.getHours(),
            minute: d.getMinutes(),
            second: d.getSeconds()
        }
    

    我正在使用正则表达式 str.replace(/^[0-9]$/g, '0$&') str.replace(/^[0-9]{1}$/g, '0$&') 例如:

    '0'.replace(/^[0-9]$/g, '0$&') // '00'
    '8'.replace(/^[0-9]$/g, '0$&') // '08'
    '12'.replace(/^[0-9]$/g, '0$&') //'12'
    
    推荐文章