繁体   English   中英

格式 JavaScript 日期为 yyyy-mm-dd

[英]Format JavaScript date as yyyy-mm-dd

我有一个格式为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 我怎样才能解决这个问题?

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

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

yourDate 是您的日期对象。

编辑@exbuddha评论中写了这个来处理时区:

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

你可以做:

 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/

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

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

2020年答案

您可以使用本机.toLocaleDateString()函数,它支持几个有用的参数,如语言环境(选择 MM/DD/YYYY 或 YYYY/MM/DD 等格式)、时区(转换日期)和格式详细信息选项(例如: 1 vs 01 vs 一月)。

例子

 const testCases = [ new Date().toLocaleDateString(), // 8/19/2020 new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}), 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) ] for (const testData of testCases) { console.log(testData) }

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

请注意,语言环境只是更改格式,如果要将特定日期转换为特定国家或城市时间,则需要使用时区参数。

将日期转换为 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);

一些答案的组合:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');
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

如果您对使用库没有任何反对意见,则可以像这样使用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');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

您可以在Date对象上使用toLocaleDateString('fr-CA')

 console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));

我还发现这些语言环境从这个语言环境列表中给出了正确的结果列表所有语言环境及其短代码?

'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'

 var localesList = ["af-ZA", "am-ET", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "arn-CL", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE", "as-IN", "az-Cyrl-AZ", "az-Latn-AZ", "ba-RU", "be-BY", "bg-BG", "bn-BD", "bn-IN", "bo-CN", "br-FR", "bs-Cyrl-BA", "bs-Latn-BA", "ca-ES", "co-FR", "cs-CZ", "cy-GB", "da-DK", "de-AT", "de-CH", "de-DE", "de-LI", "de-LU", "dsb-DE", "dv-MV", "el-GR", "en-029", "en-AU", "en-BZ", "en-CA", "en-GB", "en-IE", "en-IN", "en-JM", "en-MY", "en-NZ", "en-PH", "en-SG", "en-TT", "en-US", "en-ZA", "en-ZW", "es-AR", "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", "es-US", "es-UY", "es-VE", "et-EE", "eu-ES", "fa-IR", "fi-FI", "fil-PH", "fo-FO", "fr-BE", "fr-CA", "fr-CH", "fr-FR", "fr-LU", "fr-MC", "fy-NL", "ga-IE", "gd-GB", "gl-ES", "gsw-FR", "gu-IN", "ha-Latn-NG", "he-IL", "hi-IN", "hr-BA", "hr-HR", "hsb-DE", "hu-HU", "hy-AM", "id-ID", "ig-NG", "ii-CN", "is-IS", "it-CH", "it-IT", "iu-Cans-CA", "iu-Latn-CA", "ja-JP", "ka-GE", "kk-KZ", "kl-GL", "km-KH", "kn-IN", "kok-IN", "ko-KR", "ky-KG", "lb-LU", "lo-LA", "lt-LT", "lv-LV", "mi-NZ", "mk-MK", "ml-IN", "mn-MN", "mn-Mong-CN", "moh-CA", "mr-IN", "ms-BN", "ms-MY", "mt-MT", "nb-NO", "ne-NP", "nl-BE", "nl-NL", "nn-NO", "nso-ZA", "oc-FR", "or-IN", "pa-IN", "pl-PL", "prs-AF", "ps-AF", "pt-BR", "pt-PT", "qut-GT", "quz-BO", "quz-EC", "quz-PE", "rm-CH", "ro-RO", "ru-RU", "rw-RW", "sah-RU", "sa-IN", "se-FI", "se-NO", "se-SE", "si-LK", "sk-SK", "sl-SI", "sma-NO", "sma-SE", "smj-NO", "smj-SE", "smn-FI", "sms-FI", "sq-AL", "sr-Cyrl-BA", "sr-Cyrl-CS", "sr-Cyrl-ME", "sr-Cyrl-RS", "sr-Latn-BA", "sr-Latn-CS", "sr-Latn-ME", "sr-Latn-RS", "sv-FI", "sv-SE", "sw-KE", "syr-SY", "ta-IN", "te-IN", "tg-Cyrl-TJ", "th-TH", "tk-TM", "tn-ZA", "tr-TR", "tt-RU", "tzm-Latn-DZ", "ug-CN", "uk-UA", "ur-PK", "uz-Cyrl-UZ", "uz-Latn-UZ", "vi-VN", "wo-SN", "xh-ZA", "yo-NG", "zh-CN", "zh-HK", "zh-MO", "zh-SG", "zh-TW", "zu-ZA" ]; localesList.forEach(lcl => { if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) { console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl)); } });

只需使用这个:

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

简单而甜蜜;)

最短的

.toJSON().slice(0,10);

 var d = new Date('Sun May 11,2014' +' UTC'); // Parse as UTC let str = d.toJSON().slice(0,10); // Show as UTC console.log(str);

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/

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

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

使用Intl的 2021 解决方案。

现在所有浏览器都支持新的Intl对象。
您可以通过选择使用所需格式的“语言环境”来选择格式。

瑞典语语言环境使用格式“yyyy-mm-dd”:

// Create a date
const date = new Date(2021, 10, 28);

// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');

// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"

使用 Intl 的缺点:

  • 您不能使用此方法“取消格式化”或“解析”字符串
  • 您必须搜索所需的格式(例如在Wikipedia上),并且不能使用像“yyyy-mm-dd”这样的格式字符串

在大多数情况下(无时区处理),这就足够了:

date.toISOString().substring(0,10)

例子

var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04

你可以试试这个: 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

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

new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

或者

new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]

尝试这个!

当 ES2018 滚动时(在 chrome 中工作),您可以简单地对其进行正则表达式

(new Date())
    .toISOString()
    .replace(
        /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
        '$<year>-$<month>-$<day>'
    )

2020-07-14

或者,如果您想要没有任何库的非常通用的东西

(new Date())
    .toISOString()
    .match(
        /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
    )
    .groups

这导致提取以下内容

{
    H: "8"
    HH: "08"
    M: "45"
    MM: "45"
    S: "42"
    SS: "42"
    SSS: "42.855"
    d: "14"
    dd: "14"
    m: "7"
    mm: "07"
    timezone: "Z"
    yy: "20"
    yyyy: "2020"
}

您可以像这样使用replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>')作为顶部而不是.match(...).groups得到

14/7/'20 @ 8:45
const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');

您可以使用padstart。

padStart(n, '0') 确保字符串中至少有 n 个字符,并在其前面加上 '0' 直到达到该长度。

join('-') 连接一个数组,在每个元素之间添加“-”符号。

getMonth() 从 0 开始,因此是 +1。

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

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

不幸的是, JavaScript 的Date对象很多缺陷 任何基于Date的内置toISOString解决方案都必须与时区混淆,如该问题的其他一些答案中所述。 代表 ISO-8601 日期(没有时间)的干净解决方案由Temporal.PlainDateTemporal proposal给出。 自 2021 年 2 月起,您必须选择最适合您的解决方法。

使用带有香草字符串连接的Date

假设您的内部表示基于Date ,您可以执行手动字符串连接。 以下代码避免了Date的一些缺陷(时区、从零开始的月份、缺少 2 位格式),但可能还有其他问题。

function vanillaToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);

  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based
  const dd = String(date.getDate()).padStart(2, "0");

  if (yyyy < 1583) {
    // TODO: decide how to support dates before 1583
    throw new Error(`dates before year 1583 are not supported`);
  }

  const formatted = `${yyyy}-${mm}-${dd}`;
  console.log("vanilla", formatted);
}

Date与辅助库一起使用(例如date-fns formatISO中的 formatISO

这是一种流行的方法,但您仍然被迫将日历日期处理为Date ,它表示

独立于平台的格式的单个时刻

但是,以下代码应该可以完成工作:

import { formatISO } from "date-fns";

function dateFnsToDateOnlyIso8601() {
  // month May has zero-based index 4
  const date = new Date(2014, 4, 11);
  const formatted = formatISO(date, { representation: "date" });
  console.log("date-fns", formatted);
}

找到一个正确表示日期和时间的库

我希望有一个干净且经过实战考验的库,它可以带来自己精心设计的日期时间表示。 这个问题中任务的一个有希望的候选者是来自@js-joda/core LocalDate ,但该库不如date-fns fns 活跃。 在使用一些示例代码时,在添加可选的@js-joda/timezone后我也遇到了一些问题。

但是,核心功能有效并且对我来说看起来很干净:

import { LocalDate, Month } from "@js-joda/core";

function jodaDateOnlyIso8601() {
  const someDay = LocalDate.of(2014, Month.MAY, 11);
  const formatted = someDay.toString();
  console.log("joda", formatted);
}

尝试使用Temporal -proposal polyfill

不建议将其用于生产,但如果您愿意,可以导入未来:

import { Temporal } from "proposal-temporal";

function temporalDateOnlyIso8601() {
  // yep, month is one-based here (as of Feb 2021)
  const plainDate = new Temporal.PlainDate(2014, 5, 11);
  const formatted = plainDate.toString();
  console.log("proposal-temporal", formatted);
}

这是一种方法:

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

Date.js 非常适合这个。

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

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

这就是我想出的:

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 日。

您需要填充Date.prototype.toISOString以使其在 Internet Explorer 8 中工作,但它应该在其他任何地方都受支持。

之前的一些答案是可以的,但它们不是很灵活。 我想要一些可以真正处理更多边缘情况的东西,所以我接受了@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');

如果您使用momentjs ,现在它们包含该格式的常量YYYY-MM-DD

date.format(moment.HTML5_FMT.DATE)

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

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

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

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

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

这对我有用,以获取所需格式的当前日期(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);

 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; }
 <div id="display"></div>

new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                 (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)

不需要图书馆

只是纯 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))

PHP 兼容的日期格式

这是一个小函数,它可以采用与 PHP 函数date()相同的参数,并在 JavaScript 中返回日期/时间字符串。

请注意,并非 PHP 中的所有 date() 格式选项都受支持。 您可以扩展parts对象以创建缺少的格式标记

 /** * Date formatter with PHP "date()"-compatible format syntax. */ const formatDate = (format, date) => { if (!format) { format = 'Ymd' } if (!date) { date = new Date() } const parts = { Y: date.getFullYear().toString(), y: ('00' + (date.getYear() - 100)).toString().slice(-2), m: ('0' + (date.getMonth() + 1)).toString().slice(-2), n: (date.getMonth() + 1).toString(), d: ('0' + date.getDate()).toString().slice(-2), j: date.getDate().toString(), H: ('0' + date.getHours()).toString().slice(-2), G: date.getHours().toString(), i: ('0' + date.getMinutes()).toString().slice(-2), s: ('0' + date.getSeconds()).toString().slice(-2) } const modifiers = Object.keys(parts).join('') const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g') const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g') return format .replace(reDate, $0 => parts[$0]) .replace(reEscape, ($0, $1) => $1) } // ----- EXAMPLES ----- console.log( formatDate() ); // "2019-05-21" console.log( formatDate('H:i:s') ); // "16:21:32" console.log( formatDate('Ymd, o\\n H:i:s') ); // "2019-05-21, on 16:21:32" console.log( formatDate('Ym-d', new Date(2000000000000)) ); // "2033-05-18"

要旨

以下是formatDate()函数的更新版本和其他示例的要点: https ://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9

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

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

格式化并从 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));

此代码更改 DD MM YYYY 的顺序

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}

 const today = new Date(); // or whatever const yearFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`; } const monthFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`; } const dayFirstFormater = (date): string => { const modifiedDate = new Date(date).toISOString().slice(0, 10); return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`; } console.log(yearFirstFormater(today)); console.log(monthFirstFormater(today)); console.log(dayFirstFormater(today));

formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020

跟进https://stackoverflow.com/a/29774197/1189762这是我必须更改的关于人们在格林威治标准时间东部或西部时的偏移量:

export const toNativeHtml5InputDate = (date) => {
  if (!date) return date;

  let offset = new Date(date).getTimezoneOffset();

  offset =
    offset < 0
      ? offset * -1 // east from Greenwich Mean Time
      : offset; // west from Greenwich Mean Time

  return new Date(new Date(date).getTime() + offset * 60 * 1000)
    .toISOString()
    .split('T')[0];
};

我有一个单线器

dateInstance.toLocaleDateString().replaceAll("/", "-").split("-").reverse().join("-");

所有给出的答案都很棒,对我帮助很大。 在我的情况下,我想以 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);

我修改了 Samit Satpute 的回复如下:

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

这很容易通过我的date-shortcode包完成:

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

我们经常遇到这样的问题。 每个解决方案看起来都如此个性化。 但是看看 php,我们有办法处理不同的格式。 https://locutus.io/php/datetime/strtotime/有一个php 的 strtotime函数的端口。 我提供的一个小型开源 npm 包作为替代方式:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

请参阅datebob.js

这对我有用,如果需要测试,您可以将其直接粘贴到您的 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>

暂无
暂无

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

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