【问题标题】:Format JavaScript date as yyyy-mm-dd将 JavaScript 日期格式化为 yyyy-mm-dd
【发布时间】:2018-09-01 18:48:01
【问题描述】:

我有一个格式为Sun May 11,2014 的日期。如何使用 JavaScript 将其转换为 2014-05-11

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + '').split(' ');
    d[2] = d[2] + ',';

    return [d[0], d[1], d[2], d[3]].join(' ');
}

var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));

上面的代码给了我同样的日期格式,sun may 11,2014。我该如何解决这个问题?

【问题讨论】:

标签: javascript date formatting date-format


【解决方案1】:

你可以这样做:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}
 
console.log(formatDate('Sun May 11,2014'));

使用示例:

console.log(formatDate('Sun May 11,2014'));

输出:

2014-05-11

JSFiddle 上的演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/

【讨论】:

  • 真的在同一个语句中声明了多个变量吗? stackoverflow.com/questions/694102/…
  • @Fuser97381 同一语句中的多个变量声明不仅仅是一种审美风格偏好。这是一种危险的做法。如果您无意中失败,则在每个声明后添加一个逗号,您最终会创建全局变量。不应该鼓励什么可能成为问题的规范答案。
  • 'use strict';@bhspencer
  • 重新格式化日期字符串不应依赖于内置解析器对非标准字符串的成功解析。给定 OP 格式,它可以用更少的代码重新格式化,而无需使用 Date。
  • 这就像一个魅力,但我不明白为什么 javascript 没有对此的本地解决方案......我的意思是,我们在 2020 年,日期是网络应用程序的一个重要方面。
【解决方案2】:

这是一种方法:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));

【讨论】:

    【解决方案3】:
    format = function date2str(x, y) {
        var z = {
            M: x.getMonth() + 1,
            d: x.getDate(),
            h: x.getHours(),
            m: x.getMinutes(),
            s: x.getSeconds()
        };
        y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
            return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
        });
    
        return y.replace(/(y+)/g, function(v) {
            return x.getFullYear().toString().slice(-v.length)
        });
    }
    

    结果:

    format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
    "2014-05-11
    

    【讨论】:

    • 我喜欢这个解决方案提供的额外灵活性,而不是这个问题的其他答案。我尚未对此进行彻底测试,但对于我想要的格式(即“yyyy-MM-dd hh:mm:ss”),它可以按预期工作。
    • 你可以避免eval
    • 这里有一个版本可以更好地避免 eval 和 cmets jsfiddle.net/8904cmLd/2
    • 我从这个回复中受益。我确实用 eval 语句替换了那行 return ((v.length &gt; 1 ? "0" : "") + z[v.slice(-1)]).slice(-2);
    • “H”应该大写,而不是“h”(小)
    【解决方案4】:

    如果日期需要在所有时区都相同,例如代表数据库中的某个值,那么请务必在 JavaScript 日期对象上使用 UTC 版本的日、月、整年函数,因为这将显示在UTC 时间,并避免在某些时区出现错误。

    更好的是,使用Moment.js 日期库进行这种格式设置。

    【讨论】:

      【解决方案5】:

      我建议使用 formatDate-js 之类的东西,而不是每次都尝试复制它。只需使用支持所有主要 strftime 操作的库即可。

      new Date().format("%Y-%m-%d")
      

      【讨论】:

        【解决方案6】:

        只需利用内置的 toISOString 方法将您的日期转换为 ISO 8601 格式:

        let yourDate = new Date()
        yourDate.toISOString().split('T')[0]
        

        yourDate 是您的日期对象。

        编辑@exbuddha 写这个来处理comments 中的时区:

        const offset = yourDate.getTimezoneOffset()
        yourDate = new Date(yourDate.getTime() - (offset*60*1000))
        return yourDate.toISOString().split('T')[0]
        

        【讨论】:

        • 小心使用此方法,因为它首先将日期转换为 UTC。如果您在 + 时区并且您的时间部分是在一天的早些时候,那么它可能会回滚一天。或者,如果您在 - 时区并且您的时间部分在当天晚些时候,那么它可以向前滚动一天。
        • 试试这个:new Date(yourDateStr).toISOString().split('T')[0]
        • const offset = yourDate.getTimezoneOffset(); yourDate = new Date(yourDate.getTime() + (offset*60*1000)); yourDate.toISOString().split('T')[0] 这应该可以解决时区问题
        • now.toISOString().substring(0,10); 这是一个更简洁的替代方案,因为它提醒您 YYYY-MM-DD 是完整 iso 格式的前十个字符
        • 注意:使用@mjwrazor 评论的有用解决方案,我必须减去而不是添加偏移量才能获得正确的日期(将+ (offset 更改为- (offset
        【解决方案7】:

        一些答案​​的组合:

        var d = new Date(date);
        date = [
          d.getFullYear(),
          ('0' + (d.getMonth() + 1)).slice(-2),
          ('0' + d.getDate()).slice(-2)
        ].join('-');
        

        【讨论】:

        • 我最喜欢这个解决方案 - 易于阅读,并且不依赖于 toISOString() 以及使用该功能时潜在的时区陷阱。
        • 这是第一个不伤脑筋的。
        【解决方案8】:

        Date.js 非常适合。

        require("datejs")
        (new Date()).toString("yyyy-MM-dd")
        

        【讨论】:

          【解决方案9】:

          我使用这种方式获取格式为 yyyy-mm-dd 的日期 :)

          var todayDate = new Date().toISOString().slice(0, 10);
          console.log(todayDate);

          【讨论】:

          • 您如何处理@Luke_Baulch 在此提到的日期切换?
          • 你可以这样做: var todayDate = new Date(); todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset()); todayDate.toISOString().slice(0,10);这应该有助于避免 UTC 问题。
          • @FernandoAguilar 不过有一个疑问,我们怎么知道我们需要减去或添加偏移量?
          • var todayDate = new Date(2018, 3 - 1, 26); todayDate.toISOString().slice(0, 10); 给了我"2018-03-25"。在另一个系统上var todayDate = new Date(2018, 3 - 1, 26, 17, 0, 0); todayDate.toISOString().slice(0, 10); 给了我"2018-03-27"
          • 并不总是有效。由于 UTC 转换,它有时会减去一天。
          【解决方案10】:

          你可以试试这个:https://www.npmjs.com/package/timesolver

          npm i timesolver
          

          在你的代码中使用它:

          const timeSolver = require('timeSolver');
          const date = new Date();
          const dateString = timeSolver.getString(date, "YYYY-MM-DD");
          

          您可以使用此方法获取日期字符串:

          getString
          

          【讨论】:

            【解决方案11】:

            这对我有用,如果需要测试,您可以将其直接粘贴到 HTML 中:

            <script type="text/javascript">
                if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                             // initialize date picker widget:
                    jQuery(function($){ // On document.ready
                        $('#Date').datepicker({
                            dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                            showOtherMonths: true,
                            selectOtherMonths: true,
                            changeMonth: true,
                            minDate: '2016-10-19',
                            maxDate: '2016-11-03'
                        });
                    })
                }
            </script>
            

            【讨论】:

              【解决方案12】:

              function myYmd(D){
                  var pad = function(num) {
                      var s = '0' + num;
                      return s.substr(s.length - 2);
                  }
                  var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());
                  return Result;
              }
              
              var datemilli = new Date('Sun May 11,2014');
              document.write(myYmd(datemilli));

              【讨论】:

                【解决方案13】:

                只需使用这个:

                var date = new Date('1970-01-01'); // Or your date here
                console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());
                

                简单而甜蜜;)

                【讨论】:

                • 2 字母格式没有填充。如果日期或月份小于 10,它将显示单个数字,这就是为什么不能直接使用它。
                • 是的,但这可以简单地使用 javascript 来实现,我认为它完全符合您的要求,不是吗? @YatenderSingh
                • 是的,但请检查他想要的问题“yyyy-mm-dd”格式的标题:)
                • var old_date = new Date(date); var new_date = old_date.getFullYear() + '-' + (old_date.getMonth() + 1) + '-' + old_date.getDate()
                【解决方案14】:

                重新格式化日期字符串相当简单,例如

                var s = 'Sun May 11,2014';
                
                function reformatDate(s) {
                  function z(n){return ('0' + n).slice(-2)}
                  var months = [,'jan','feb','mar','apr','may','jun',
                                 'jul','aug','sep','oct','nov','dec'];
                  var b = s.split(/\W+/);
                  return b[3] + '-' +
                    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
                    z(b[2]);
                }
                
                console.log(reformatDate(s));

                【讨论】:

                  【解决方案15】:

                  所有给出的答案都很好,对我帮助很大。在我的情况下,我想以 yyyy mm dd 格式获取当前日期以及 date-1。这对我有用。

                  var endDate = new Date().toISOString().slice(0, 10); // To get the Current Date in YYYY MM DD Format
                  
                  var newstartDate = new Date();
                  newstartDate.setDate(newstartDate.getDate() - 1);
                  var startDate = newstartDate.toISOString().slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
                  alert(startDate);
                  

                  【讨论】:

                    【解决方案16】:

                    toISOString() 假定您的日期是当地时间并将其转换为 UTC。你会得到一个不正确的日期字符串。

                    下面的方法应该返回你所需要的。

                    Date.prototype.yyyymmdd = function() {         
                    
                        var yyyy = this.getFullYear().toString();                                    
                        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
                        var dd  = this.getDate().toString();             
                    
                        return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
                    };
                    

                    来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/

                    【讨论】:

                      【解决方案17】:

                      答案的另一种组合。可读性很好,但有点冗长。

                      function getCurrentDayTimestamp() {
                        const d = new Date();
                      
                        return new Date(
                          Date.UTC(
                            d.getFullYear(),
                            d.getMonth(),
                            d.getDate(),
                            d.getHours(),
                            d.getMinutes(),
                            d.getSeconds()
                          )
                        // `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
                        // and we want the first part ("2017-08-22")
                        ).toISOString().slice(0, 10);
                      }
                      

                      【讨论】:

                        【解决方案18】:

                        这些答案都没有让我很满意。我想要一个跨平台的解决方案,让我在本地时区度过一天,而无需使用任何外部库。

                        这是我想出的:

                        function localDay(time) {
                          var minutesOffset = time.getTimezoneOffset()
                          var millisecondsOffset = minutesOffset*60*1000
                          var local = new Date(time - millisecondsOffset)
                          return local.toISOString().substr(0, 10)
                        }
                        

                        这应该返回日期中的日期,格式为 YYYY-MM-DD,在日期引用的时区中。

                        例如,localDay(new Date("2017-08-24T03:29:22.099Z")) 将返回 "2017-08-23",即使它已经是 UTC 的 24 日。

                        您需要 polyfillDate.prototype.toISOString 才能在 Internet Explorer 8 中工作,但其他地方都应该支持它。

                        【讨论】:

                        • 也许值得注意的是,如果你足够落后于 UTC(例如在美国),它只会给你 2017-08-23。
                        【解决方案19】:

                        我修改Samit Satpute's response如下:

                        var newstartDate = new Date();
                        // newstartDate.setDate(newstartDate.getDate() - 1);
                        var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
                        console.log(startDate);

                        【讨论】:

                          【解决方案20】:

                          检索年、月和日,然后将它们放在一起。直接、简单、准确。

                          function formatDate(date) {
                              var year = date.getFullYear().toString();
                              var month = (date.getMonth() + 101).toString().substring(1);
                              var day = (date.getDate() + 100).toString().substring(1);
                              return year + "-" + month + "-" + day;
                          }
                          
                          //Usage example:
                          alert(formatDate(new Date()));

                          【讨论】:

                            【解决方案21】:

                            通过我的date-shortcode 包很容易实现:

                            const dateShortcode = require('date-shortcode')
                            dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
                            //=> '2014-05-11'
                            

                            【讨论】:

                            • 我真的不赞成。这绝对是完成 OP 所要求的一种方式。
                            【解决方案22】:

                            之前的一些答案是可以的,但它们不是很灵活。我想要一些可以真正处理更多边缘情况的东西,所以我接受了@orangleliu 的回答并对其进行了扩展。 https://jsfiddle.net/8904cmLd/1/

                            function DateToString(inDate, formatString) {
                                // Written by m1m1k 2018-04-05
                            
                                // Validate that we're working with a date
                                if(!isValidDate(inDate))
                                {
                                    inDate = new Date(inDate);
                                }
                            
                                // See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
                                //formatString = CountryCodeToDateFormat(formatString);
                            
                                var dateObject = {
                                    M: inDate.getMonth() + 1,
                                    d: inDate.getDate(),
                                    D: inDate.getDate(),
                                    h: inDate.getHours(),
                                    m: inDate.getMinutes(),
                                    s: inDate.getSeconds(),
                                    y: inDate.getFullYear(),
                                    Y: inDate.getFullYear()
                                };
                            
                                // Build Regex Dynamically based on the list above.
                                // It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
                                var dateMatchRegex = joinObj(dateObject, "+|") + "+";
                                var regEx = new RegExp(dateMatchRegex,"g");
                                formatString = formatString.replace(regEx, function(formatToken) {
                                    var datePartValue = dateObject[formatToken.slice(-1)];
                                    var tokenLength = formatToken.length;
                            
                                    // A conflict exists between specifying 'd' for no zero pad -> expand
                                    // to '10' and specifying yy for just two year digits '01' instead
                                    // of '2001'.  One expands, the other contracts.
                                    //
                                    // So Constrict Years but Expand All Else
                                    if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
                                    {
                                        // Expand single digit format token 'd' to
                                        // multi digit value '10' when needed
                                        var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
                                    }
                                    var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
                                    return (zeroPad + datePartValue).slice(-tokenLength);
                                });
                            
                                return formatString;
                            }
                            

                            示例用法:

                            DateToString('Sun May 11,2014', 'MM/DD/yy');
                            DateToString('Sun May 11,2014', 'yyyy.MM.dd');
                            DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
                            

                            【讨论】:

                            • 不错的干净和评论的解决方案。然而,我对第一个论点持怀疑态度,如果不被识别为有效日期,它会默默地被一个新的日期替换。我宁愿将此“可选默认值”作为第二个参数,并返回某种异常(可能是一个简单的“无效日期格式”返回字符串)以防格式无法识别,因此出现错误 明确测试人员/用户
                            【解决方案23】:

                            将日期转换为 yyyy-mm-dd 格式的最简单方法是:

                            var date = new Date("Sun May 11,2014");
                            var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                                                .toISOString()
                                                .split("T")[0];
                            

                            它是如何工作的:

                            • new Date("Sun May 11,2014") 将字符串 "Sun May 11,2014" 转换为日期对象,该对象表示基于当前语言环境(主机系统设置)的时区中的时间 Sun May 11 2014 00:00:00
                            • new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) 通过减去时区偏移量将您的日期转换为与 UTC(标准时间)中的时间 Sun May 11 2014 00:00:00 对应的日期对象
                            • .toISOString() 将日期对象转换为 ISO 8601 字符串 2014-05-11T00:00:00.000Z
                            • .split("T") 将字符串拆分为数组 ["2014-05-11", "00:00:00.000Z"]
                            • [0] 获取该数组的第一个元素

                            演示

                            var date = new Date("Sun May 11,2014");
                            var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                                                .toISOString()
                                                .split("T")[0];
                            
                            console.log(dateString);

                            【讨论】:

                            • 没有其他人对这是最简单的方法感到震惊??
                            • @JoeDevmon :我不明白这与这里有什么关系。 - (date.getTimezoneOffset() * 60000 ) 位应消除任何时区差异,包括夏令时的影响。
                            • @JohnSlegers 这就是我的想法,但在某些情况下,我仍然是前一天。我重构了,你的例子现在可以工作了。我一定有一个奇怪的日期字符串或其他东西。感谢您坚持并指出这一点。 +1 ?
                            • 我在 SO 和其他网站上进行了高低搜索,以找到处理 JS 中日期的时区问题的最佳方法,并且毫无疑问,这是迄今为止最简单和最好的。谢谢!
                            • 很遗憾,但这是将 js 日期格式化为您需要的字符串的最简单方法。我是 js 新手,但在 java 中,将日期格式化为任何格式要容易 100 倍。这就是为什么认为有更简单的方法,但在我尝试了不同的解决方案后,我选择了这个。谢谢你的回答。
                            【解决方案24】:

                            如果您对使用库没有任何反对意见,您可以像这样使用Moments.js 库:

                            var now = new Date();
                            var dateString = moment(now).format('YYYY-MM-DD');
                            
                            var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
                            &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"&gt;&lt;/script&gt;

                            【讨论】:

                            • 很酷的解决方案,但它是一个 300kb 的包
                            • 在 react 项目中应用:npm install moment --saveimport moment from 'moment';const showEventDate = moment(your-date-here).format('YYYY-MM-DD; HH:mm A'); 以任何格式呈现日期/时间的纯粹解决方案。它提供带有 AM/PM 的本地日期时间以及您只需要更改格式的任何内容。 Moment.js 还提供简单的日期/时间计数解决方案。
                            • @theTradeCoder 正如 Adam 上面提到的那样,moment 的大小非常大(我认为它更像是 67kb,但仍然如此)所以在评估任何依赖项的易用性和实用性时应该考虑到这一点。还有更小的替代品(day.js = 2kb)。
                            • 只是关于 moment.js 库的更新 - moment.js 已经停产。
                            【解决方案25】:

                            还要考虑时区,如果没有任何库,这个单行应该很好:

                            new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
                            

                            【讨论】:

                              【解决方案26】:

                              这有助于我以所需格式 (YYYYMMDD HH:MM:SS) 获取当前日期:

                              var d = new Date();
                              
                              var date1 = d.getFullYear() + '' +
                                          ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
                                          '' +
                                          (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
                              
                              var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
                                          ':' +
                                          (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
                                          ':' +
                                          (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());
                              
                              print(date1+' '+time1);
                              

                              【讨论】:

                                【解决方案27】:

                                var d = new Date("Sun May 1,2014");
                                
                                var year  = d.getFullYear();
                                var month = d.getMonth() + 1;
                                var day   = d.getDate(); 
                                
                                month = checkZero(month);             
                                day   = checkZero(day);
                                
                                var date = "";
                                
                                date += year;
                                date += "-";
                                date += month;
                                date += "-";
                                date += day;
                                
                                document.querySelector("#display").innerHTML = date;
                                    
                                function checkZero(i) 
                                {
                                    if (i < 10) 
                                    {
                                        i = "0" + i
                                    };  // add zero in front of numbers < 10
                                
                                    return i;
                                }
                                &lt;div id="display"&gt;&lt;/div&gt;

                                【讨论】:

                                  【解决方案28】:
                                  new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                                                   (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
                                  

                                  【讨论】:

                                    【解决方案29】:

                                    格式化并从 hashmap 数据中查找最大和最小日期:

                                    var obj = {"a":'2001-15-01', "b": '2001-12-02' , "c": '2001-1-03'};
                                    
                                    function findMaxMinDate(obj){
                                      let formatEncode = (id)=> { let s = id.split('-'); return `${s[0]+'-'+s[2]+'-'+s[1]}`}
                                      let formatDecode = (id)=> { let s = id.split('/'); return `${s[2]+'-'+s[0]+'-'+s[1]}`}
                                      let arr = Object.keys( obj ).map(( key )=> { return new Date(formatEncode(obj[key])); });
                                      let min = new Date(Math.min.apply(null, arr)).toLocaleDateString();
                                      let max = new Date(Math.max.apply(null, arr)).toLocaleDateString();
                                      return {maxd: `${formatDecode(max)}`, mind:`${formatDecode(min)}`}
                                    }
                                    
                                    console.log(findMaxMinDate(obj));

                                    【讨论】:

                                    • 这与问题有什么关系(格式化日期)?
                                    【解决方案30】:

                                    不需要库

                                    只是纯 JavaScript。

                                    以下示例获取从今天开始的最后两个月:

                                    var d = new Date()
                                    d.setMonth(d.getMonth() - 2);
                                    var dateString = new Date(d);
                                    console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))

                                    【讨论】:

                                    • 危险。在这种情况下,您将忽略时区偏移量。
                                    • 你说的危险是指每天几个小时返回错误的日期?
                                    猜你喜欢
                                    • 1970-01-01
                                    • 2015-11-03
                                    • 2013-03-18
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2013-11-01
                                    • 1970-01-01
                                    • 2016-01-02
                                    相关资源
                                    最近更新 更多