Javascript 如何获取 YYYY-MM-DD 格式的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32192922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:43:57  来源:igfitidea点击:

How do I get a date in YYYY-MM-DD format?

javascriptdate

提问by OneStig

Normally if I wanted to get the date I could just do something like

通常如果我想得到日期,我可以做一些类似的事情

var d = new Date(); console.log(d);

var d = new Date(); console.log(d);

The problem with doing that, is when I run that code, it returns:

这样做的问题是,当我运行该代码时,它返回:

Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)

2015 年 8 月 24 日星期一 4:20:00 GMT-0800(太平洋标准时间)

How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:

我怎样才能让 Date() 方法以“MM-DD-YYYY”格式返回一个值,以便它返回如下内容:

8/24/2015

8/24/2015

Or, maybe MM-DD-YYYY H:M

或者,也许 MM-DD-YYYY H:M

8/24/2016 4:20

2016/8/24 4:20

回答by leaksterrr

Just use the built-in .toISOString()method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.

只需使用内置的.toISOString()方法,像这样:toISOString().split('T')[0]。简单,干净,全部在一行中。

var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>

Please note that the timezone of the formatted string is UTCrather than local time.

请注意,格式化字符串的时区是UTC而不是本地时间。

回答by Patrick2607

The below code is a way of doing it. If you have a date, pass it to the convertDate()function and it will return a string in the YYYY-MM-DD format:

下面的代码是一种方法。如果你有一个日期,把它传递给convertDate()函数,它会返回一个 YYYY-MM-DD 格式的字符串:

var todaysDate = new Date();

function convertDate(date) {
  var yyyy = date.getFullYear().toString();
  var mm = (date.getMonth()+1).toString();
  var dd  = date.getDate().toString();

  var mmChars = mm.split('');
  var ddChars = dd.split('');

  return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}

console.log(convertDate(todaysDate)); // Returns: 2015-08-25

回答by DevonDahon

Yet another way:

还有一种方式:

var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">

回答by cezar

What you want to achieve can be accomplished with native JavaScript. The object Datehas methods that generate exactly the output you wish.
Here are code examples:

您想要实现的目标可以通过原生 JavaScript 实现。该对象Date具有生成您希望的输出的方法。
下面是代码示例:

var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM

There is really no need to reinvent the wheel.

真的没有必要重新发明轮子。

回答by Omar Khaiyam

function formatdate(userDate){
  var omar= new Date(userDate);
  y  = omar.getFullYear().toString();
  m = omar.getMonth().toString();
  d = omar.getDate().toString();
  omar=y+m+d;
  return omar;
}
console.log(formatDate("12/31/2014"));

回答by tylerwillis

If you're not opposed to adding a small library, Date-Mirror (NPMor unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.

如果您不反对添加小型库,Date-Mirror(NPMunpkg)允许您将 YYYY-MM-DD 中的现有日期格式化为您喜欢的任何日期字符串格式。

date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8

Disclaimer: I developed Date-Mirror.

免责声明:我开发了 Date-Mirror。

回答by Lou Bagel

Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.

这是我创建的一个简单函数,当我继续从事一个项目时,我经常需要以这种格式获取今天、昨天和明天的日期。

function returnYYYYMMDD(numFromToday = 0){
  let d = new Date();
  d.setDate(d.getDate() + numFromToday);
  const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
  const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
  return `${d.getFullYear()}-${month}-${day}`;
}

console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow

Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.

可以很容易地修改为传递一个日期,但在这里你传递一个数字,它会从今天起返回那么多天。

回答by usman tahir

By using moment.js library, you can do it:

通过使用 moment.js 库,您可以做到:

var datetime = new Date("2015-09-17 15:00:00"); datetime = moment(datetime).format("YYYY-MM-DD");

var datetime = new Date("2015-09-17 15:00:00"); datetime = moment(datetime).format("YYYY-MM-DD");

回答by user12094423

var today = new Date();

function formatDate(date) {
 var dd = date.getDate();
        var mm = date.getMonth() + 1; //January is 0!
        var yyyy = date.getFullYear();
        if (dd < 10) {
          dd = '0' + dd;
        }
        if (mm < 10) {
          mm = '0' + mm;
        }
        //return dd + '/' + mm + '/' + yyyy;
             return yyyy + '/' + mm + '/' +dd ;

}

console.log(formatDate(today));

回答by Fisher

If you are trying to get the 'local-ISO' date string. Try the code below.

如果您尝试获取“local-ISO”日期字符串。试试下面的代码。

function (date) {
    return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}

+dateGet milliseconds from a date.

+date从日期获取毫秒数。

Ref: Date.prototype.getTimezoneOffsetHave fun with it :)

参考:Date.prototype.getTimezoneOffset玩得开心:)