【问题标题】:How to get year/month/day from a date object?如何从日期对象中获取年/月/日?
【发布时间】:2011-01-02 01:33:28
【问题描述】:

alert(dateObj)Wed Dec 30 2009 00:00:00 GMT+0800

如何获取2009/12/30格式的日期?

【问题讨论】:

  • 您想要 UTC 日期和时间?

标签: javascript date


【解决方案1】:
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate = year + "/" + month + "/" + day;

或者您可以设置新日期并给出上述值

【讨论】:

  • 请记住:一月=0,二月=1,依此类推。
  • getMonthgetUTCMonth有什么区别?
  • UTC 将返回世界时。如果你想要当地时间使用 getMonth
  • getUTCDay() 应替换为 getUTCDate(),因为 day 是一周中的天数 (0-6),而 date 是一个月中的天数 (1-31)。
  • 我相信这个响应仍然有缺陷。 getUTCDate() 确实会返回当月的日期,但在英格兰。例如,如果我输入: var d = new Date("July 21, 1983 01:15:00"); d.getDate() 返回 21 但 d.getUTCDate() 只返回 20 这是因为在法国(我所在的地方)早上 01:15,英格兰仍然是 23:15。要获取原始日期中的日期,您应该使用 getDate()。
【解决方案2】:
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"

【讨论】:

  • 我认为这对于第三种情况可能会更好 new Date().toISOString().split('T')[0].replace(/-/g, '/');跨度>
【解决方案3】:
var dt = new Date();

dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();

由于月份索引为 0,因此您必须将其增加 1。

编辑

有关日期对象函数的完整列表,请参阅

Date

getMonth()

根据当地时间返回指定日期的月份(0-11)。

getUTCMonth()

根据通用时间返回指定日期的月份(0-11)。

【讨论】:

  • 需要括号。否则 10 月将显示为 91 月(因为 9 + 1 = 91 in stringland)
  • 应该是 dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
【解决方案4】:

为什么不使用toISOString()slice 或简单的toLocaleDateString() 方法?

在这里查看:

const d = new Date() // today, now

console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD

console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY

【讨论】:

  • 这只是救了我的命,你太棒了!!
  • 对于那些从 Mongo 回来并在year/month/day 需要他们的人,这就是你的答案^^^。示例:new Date("2021-01-01T00:00:00.000Z").toISOString().slice(0,10)
  • 很好的答案!也许有一天会有一个.toISODateString() 这样做。
  • 这给了我一个错误的日期,new Date(1618264800000).toLocaleDateString() => "13.4.2021",但 new Date(1618264800000).toISOString().slice(0, 10) => "2021-04-12"。所以这是一天的差异。
  • : @dude 这取决于 UTC 或地区时间,请参阅 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
【解决方案5】:

我建议你使用 Moment.js http://momentjs.com/

那么你可以这样做:

moment(new Date()).format("YYYY/MM/DD");

注意:如果您想要当前的 TimeDate,实际上不需要添加 new Date(),我只是将它添加为您可以将日期对象传递给它的引用。对于当前的 TimeDate 这也适用:

moment().format("YYYY/MM/DD");

【讨论】:

  • 如果您希望添加依赖项,则此答案很好 - 如果从 2019 年开始,day.js 是 moment.js 的更轻量级替代方案,可以考虑 - github.com/iamkun/dayjs。还提到了 Luxon 和 date-fns。
【解决方案6】:

2021 年答案

您可以使用原生的.toLocaleDateString() 函数,它支持几个有用的参数,如 locale(选择格式,如 MM/DD/YYYY 或 YYYY/MM/DD)、timezone(转换日期)和格式详细信息选项(例如:1 vs 01 vs January)。

示例

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

请注意,有时要以您想要的特定格式输出日期,您必须找到与该格式兼容的语言环境。 您可以在此处找到语言环境示例:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

请注意,locale 只是更改格式,如果您想将特定日期转换为特定国家或城市的等效时间,则需要使用 timezone 参数.

【讨论】:

    【解决方案7】:
    var date = new Date().toLocaleDateString()
    "12/30/2009"
    

    【讨论】:

    • 要比较两个日期,这个答案是最重要的。谢谢!
    【解决方案8】:

    信息

    如果需要 2 位数的月份和日期(2016/01/01 与 2016/1/1)

    代码

    var dateObj = new Date();
    var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
    var date = ('0' + dateObj.getDate()).slice(-2);
    var year = dateObj.getFullYear();
    var shortDate = year + '/' + month + '/' + date;
    alert(shortDate);
    

    输出

    2016/10/06

    小提琴

    https://jsfiddle.net/Hastig/1xuu7z7h/

    学分

    更多信息来自credit to this answer

    更多

    要了解有关.slice 的更多信息,w3schools 的try it yourself editor 帮助我更好地了解了如何使用它。

    【讨论】:

    • 但是如果日期设置为 12 月,不会提前到明年 1 月?
    【解决方案9】:

    使用 Date 获取方法。

    http://www.tizag.com/javascriptT/javascriptdate.php

    http://www.htmlgoodies.com/beyond/javascript/article.php/3470841

    var dateobj= new Date() ;
    var month = dateobj.getMonth() + 1;
    var day = dateobj.getDate() ;
    var year = dateobj.getFullYear();
    

    【讨论】:

    • JavaScript Date 对象的月份是零索引的。一定要加 1,否则 12 月就是 11 月;十一月变成十月等等
    • @Aseem 应该只是需要 +1 的月份
    【解决方案10】:

    漂亮的格式化插件:http://blog.stevenlevithan.com/archives/date-time-format

    你可以这样写:

    var now = new Date();
    now.format("yyyy/mm/dd");
    

    【讨论】:

      【解决方案11】:
      let dateObj = new Date();
      
      let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
      

      作为参考,您可以查看以下详细信息

      new Date().getDate()          // Return the day as a number (1-31)
      new Date().getDay()           // Return the weekday as a number (0-6)
      new Date().getFullYear()      // Return the four digit year (yyyy)
      new Date().getHours()         // Return the hour (0-23)
      new Date().getMilliseconds()  // Return the milliseconds (0-999)
      new Date().getMinutes()       // Return the minutes (0-59)
      new Date().getMonth()         // Return the month (0-11)
      new Date().getSeconds()       // Return the seconds (0-59)
      new Date().getTime()          // Return the time (milliseconds since January 1, 1970)
      

      let dateObj = new Date();
      
      let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
      
      console.log(myDate)

      // 返回分钟 (0-59) new Date().getMonth() // 返回月份 (0-11) new Date().getSeconds() // 返回秒数 (0-59) new Date().getTime() // 返回时间(自 1970 年 1 月 1 日以来的毫秒数)

      【讨论】:

        【解决方案12】:

        欧洲(英语/西班牙语)格式
        我你也需要得到当天,你可以用这个。

        function getFormattedDate(today) 
        {
            var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
            var day  = week[today.getDay()];
            var dd   = today.getDate();
            var mm   = today.getMonth()+1; //January is 0!
            var yyyy = today.getFullYear();
            var hour = today.getHours();
            var minu = today.getMinutes();
        
            if(dd<10)  { dd='0'+dd } 
            if(mm<10)  { mm='0'+mm } 
            if(minu<10){ minu='0'+minu } 
        
            return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
        }
        
        var date = new Date();
        var text = getFormattedDate(date);
        


        *对于西班牙语格式,只需翻译 WEEK 变量。

        var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
        


        输出:星期一 - 2015 年 11 月 16 日 14:24

        【讨论】:

          【解决方案13】:

          使用接受的答案,1 月 1 日将显示如下:2017/1/1

          如果你更喜欢2017/01/01,你可以使用:

          var dt = new Date();
          var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
          

          【讨论】:

            【解决方案14】:

            这是使用模板文字获取年/月/日的一种更简洁的方法:

            var date = new Date();
            var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
            console.log(formattedDate);

            【讨论】:

              【解决方案15】:

              它是动态的它将从用户的浏览器设置中收集语言

              使用 option 对象中的 minuteshour 属性来处理它们。 您可以使用 long 值来表示月份,例如 8 月 23 日等...

              function getDate(){
               const now = new Date()
               const option = {
                day: 'numeric',
                month: 'numeric',
                year: 'numeric'
               }
               const local = navigator.language
               labelDate.textContent = `${new 
               Intl.DateTimeFormat(local,option).format(now)}`
              }
              getDate()
              

              【讨论】:

                【解决方案16】:

                您可以简单地使用这一行代码以年-月-日格式获取日期

                var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
                

                【讨论】:

                  【解决方案17】:

                  如果您将日期 obj 或 js 时间戳传递给它,我正在使用它:

                  getHumanReadableDate: function(date) {
                      if (date instanceof Date) {
                           return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
                      } else if (isFinite(date)) {//timestamp
                          var d = new Date();
                          d.setTime(date);
                          return this.getHumanReadableDate(d);
                      }
                  }
                  

                  【讨论】:

                    【解决方案18】:

                    ES2018 引入了正则表达式捕获组,您可以使用它来捕获日、月和年:

                    const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2});
                    const results = REGEX.exec('2018-07-12');
                    console.log(results.groups.year);
                    console.log(results.groups.month);
                    console.log(results.groups.day);
                    

                    这种方法的优点是可以捕获非标准字符串日期格式的日、月、年。

                    参考。 https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/

                    【讨论】:

                    • 问题是专门询问如何从 Date 对象中格式化“月/日/年”中的日期。正则表达式中的捕获组在这里不适用。
                    猜你喜欢
                    • 2021-11-03
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-05-06
                    • 2020-04-29
                    • 1970-01-01
                    相关资源
                    最近更新 更多