【问题标题】:JavaScript how to remove the day name from date formate? [duplicate]JavaScript如何从日期格式中删除日期名称? [复制]
【发布时间】:2021-03-26 11:44:11
【问题描述】:

对于特定的应用程序,我需要将我的日期格式从

2021 年 3 月 26 日星期五 16:00:01 GMT+0400(海湾标准时间)

2023 年 1 月 1 日 00:00:00 GMT+03:00

我该怎么做?

【问题讨论】:

    标签: javascript date format


    【解决方案1】:

    这就是我解决格式问题的方法:

    
    //1. Get closing time from event
    time = new Date(item.returnValues['closingTime'] * 1000);
                        
    //2. Formatting the date for the date counter input
    const options = {  year: 'numeric', month: 'long', day: 'numeric' };
    firstPart= time.toLocaleDateString('en-US', options);
                       
    //3. Get original GMT time from the var time
    secondPart = time.toString().slice(15, 24); 
    secondPart = secondPart.concat(" GMT+04:00 ");
                        
    //4. concat the two strings into the desired form
    ct = firstPart.concat(secondPart);
                       
    

    【讨论】:

      【解决方案2】:

      基于mozila's documents,当时间要显示为字符串时,前三个字母总是代表工作日名称,它们将与其他数据用一个空格分开,所以我们可以省略前4个字符(来自最终字符串的 3 个首字母 + 后跟空格),函数如下:

      let sampleDate = Date();
      
      function sliceDayFromTime(dateTime) {
         return dateTime.slice(4);
      }
      
      console.log(sliceDayFromTime(sampleDate));
      

      为了使用更高级的格式,您可以使用Intl.DateTimeFormat,这是一个启用语言敏感的日期和时间格式的对象。

      对于你上面提到的具体例子,我相信下面的代码很有用

      var sampleDate = new Date();
      
      var formatter = new Intl.DateTimeFormat('en-us', {
        month: 'long',
        year: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric',
        hour12: false,
        timeZoneName: 'short'
      });
      
      function minimalFormatDate(date) {
          return formatter.format(date);
      }
      
      function advancedFromatDate(date) {
          return formatter.formatToParts(date).map(({type, value}, index) => {
              if (type === 'literal' && index === 5) {
                  return ' '
              }
              return value;
          }).join('');
      }
      
      console.log('minimal formating example: ', minimalFormatDate(sampleDate));
      console.log('advanced formating example: ', advancedFromatDate(sampleDate));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-15
        • 1970-01-01
        • 2010-11-06
        • 2018-05-05
        • 1970-01-01
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多