简体   繁体   English

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

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

Normally if I wanted to get the date I could just do something like通常,如果我想得到日期,我可以做类似的事情

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 2015 年 8 月 24 日

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

8/24/2016 4:20 8/24/2016 4:20

Just use the built-in .toISOString() method like so: toISOString().split('T')[0] .只需使用内置的.toISOString()方法,如下所示: toISOString().split('T')[0] Simple, clean and all in a single line.简单,干净,全部在一行中。

 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 UTC rather than local time.请注意,格式化字符串的时区是UTC而不是本地时间。

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

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">

What you want to achieve can be accomplished with native JavaScript.您想要实现的目标可以通过原生 JavaScript 实现。 The object Date has methods that generate exactly the output you wish.对象Date具有生成您想要的输出的方法。
Here are code examples:下面是代码示例:

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 using moment.js library, you can do it:通过使用 moment.js 库,您可以做到:

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

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"));
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));

If you are trying to get the 'local-ISO' date string.如果您尝试获取“local-ISO”日期字符串。 Try the code below.试试下面的代码。

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

+date Get milliseconds from a date. +date+date获取毫秒数。

Ref: Date.prototype.getTimezoneOffset Have fun with it :)参考: Date.prototype.getTimezoneOffset玩得开心:)

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.可以很容易地修改为传递一个日期,但在这里你传递一个数字,它会从今天起返回那么多天。

If you're not opposed to adding a small library, Date-Mirror ( NPM or 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。

This will convert a unix timestamp to local date (+ time)这会将 unix 时间戳转换为本地日期(+时间)

function UnixTimeToLocalDate = function( unix_epoch_time )
{
    var date,
        str;
        
    date = new Date( unix_epoch_time * 1000 );
    
    str = date.getFullYear() + '-' +
          (date.getMonth() + 1 + '').padStart( 2, '0' )  + '-' +
          (date.getDate() + '').padStart( 2, '0' );

    // If you need hh:mm:ss too then

    str += ' ' +
          (date.getHours()   + '').padStart( 2, '0' ) + ':' +
          (date.getMinutes() + '').padStart( 2, '0' ) + ':' +
          (date.getSeconds() + '').padStart( 2, '0' );
          
    return str;
}

If you want a text format that's good for sorting use:如果您想要一种适合排序的文本格式,请使用:

function formatDateYYYYMMDDHHMMSS(date){
  // YYYY-MM-DD HH:MM:SS
  const datePart = date.toISOString().split("T")[0]
  const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
  return datePart + timePart
}

As prototype:作为原型:

Date.prototype.toSortString = function(){
  const date = new Date(this.valueOf());
  return date.toISOString().split("T")[0] + 
         date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}

Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01' fullYear-fullMonth-FullDay 的简单一行优雅解决方案为 '2000-01-01'

new Date().toLocaleDateString("fr-CA", 
   {year:"numeric", month: "2-digit", day:"2-digit"}
)

 const padTo2Digits = num => { return num.toString().padStart(2, '0') } const formatDate = date => { return [ date.getFullYear(), padTo2Digits(date.getMonth() + 1), padTo2Digits(date.getDate()) ].join('-') } let value = formatDate(new Date()) document.getElementById('dayFormatUS').innerHTML = value const transformDate = date => { const convert = date.split('-').reverse() return convert.join('/') } document.getElementById('dayFormatBR').innerHTML = transformDate(value)
 <div> Format US - <span id='dayFormatUS'></span> </div> <div> Format BR - <span id='dayFormatBR'></span> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM