Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将JavaScript日期格式化为yyyy mm dd_Javascript_Date_Formatting_Date Format - Fatal编程技术网

将JavaScript日期格式化为yyyy mm dd

将JavaScript日期格式化为yyyy mm dd,javascript,date,formatting,date-format,Javascript,Date,Formatting,Date Format,我有一个日期,格式是2014年5月11日太阳报。如何使用JavaScript将其转换为2014-05-11 函数任务日期(dateMilli){ 变量d=(新日期(dateMilli)+''。拆分(''); d[2]=d[2]+','; 返回[d[0]、d[1]、d[2]、d[3]。加入(“”); } var datemilli=Date.parse('Sun May 112014'); console.log(taskDate(datemilli))您可以执行以下操作: 函数格式日期(日期

我有一个日期,格式是2014年5月11日太阳报。如何使用JavaScript将其转换为
2014-05-11

函数任务日期(dateMilli){
变量d=(新日期(dateMilli)+''。拆分('');
d[2]=d[2]+',';
返回[d[0]、d[1]、d[2]、d[3]。加入(“”);
}
var datemilli=Date.parse('Sun May 112014');
console.log(taskDate(datemilli))您可以执行以下操作:

函数格式日期(日期){
var d=新日期(日期),
月份=“”+(d.getMonth()+1),
日期=“”+d.getDate(),
year=d.getFullYear();
如果(月长<2)
月份='0'+月份;
如果(日长<2)
天='0'+天;
返回[年、月、日]。加入('-');
}

console.log(formattate('Sun-May 112014'))这里有一种方法:

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));
结果:
我建议使用类似的方法,而不是每次都尝试复制它。只需使用支持所有主要strftime操作的库

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

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

const yourDate = new Date()
yourDate.toISOString().split('T')[0]
其中yourDate是日期对象

编辑:编写此命令是为了在以下位置处理时区:


以下是一些答案的组合:

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

Date.js非常适合这样做

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

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


var todayDate=new Date().toISOString().slice(0,10);
console.log(今天)您可以尝试以下方法:

在代码中使用它:

const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
您可以使用以下方法获取日期字符串:

getString
函数myYmd(D){
var pad=函数(num){
变量s='0'+num;
返回s.substr(s.length-2);
}
var Result=D.getFullYear()+'-'+pad((D.getMonth()+1))+'-'+pad(D.getDate());
返回结果;
}
var datemilli=新日期(“2014年5月11日太阳”);
文件写入(myYmd(datemilli))只需使用以下内容:

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

简单而甜美;)

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

var s='2014年5月11日太阳报';
函数重新格式化日期{
函数z(n){return('0'+n).slice(-2)}
变量月份=[,'一月','二月','三月','四月','五月','六月',
‘七月’、‘八月’、‘九月’、‘十月’、‘十一月’、‘十二月’;
var b=s.split(/\W+/);
返回b[3]+'-'+
z(months.indexOf(b[1].substr(0,3).toLowerCase())+'-'+
z(b[2]);
}
控制台日志(重新格式化日期)
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]);
};

资料来源:

这些答案我都不满意。我想要一个跨平台的解决方案,让我可以在本地时区工作,而不用使用任何外部库

这就是我想到的:

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(新日期(“2017-08-24T03:29:22.099Z”)
将返回
“2017-08-23”
,即使它已经是UTC的第24个


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

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

函数格式日期(日期){
var year=date.getFullYear().toString();
var month=(date.getMonth()+101.toString().substring(1);
var day=(date.getDate()+100).toString()子字符串(1);
返回年份+“-”+月份+“-”+天;
}
//用法示例:

警报(formatDate(新日期())前面的一些答案是可以的,但它们不是很灵活。我想要一些能够处理更多边缘情况的东西,所以我接受了@orangleliu的答案并对其进行了扩展


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

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

  • 新建日期(“2014年5月11日太阳”)
    将字符串
    “2014年5月11日太阳”
    转换为一个日期对象,该对象表示基于当前区域设置(主机系统设置)的时区中的时间
    2014年5月11日00:00:00
  • 新日期(Date.getTime()-(Date.getTimezoneOffset()*60000))
    通过减去时区偏移量,将日期转换为日期对象,该对象与时间2014年5月11日星期日00:00:00
UTC(标准时间)中的时间相对应
  • .toISOString()
    将日期对象转换为ISO 8601字符串
    2014-05-11T00:00:00.000Z
  • .split(“T”)
    将字符串拆分为数组
    [“2014-05-11”,“00:00:00.000Z”]
  • [0]
    获取该数组的第一个元素

  • 演示
    var日期=新日期(“2014年5月11日太阳”);
    var dateString=新日期(Date.getTime()-(Date.getTimezoneOffset()*60000))
    .toISOString()
    .分割(“T”)[0];
    
    log(日期字符串)如果您不反对使用库,您可以这样使用库:

    var now=newdate();
    var dateString=moment(now).format('YYYY-MM-DD');
    var dateStringWithTime=moment(now).format('YYYY-MM-DD HH:MM:ss')
    
    <>代码> <代码> 考虑到时区,这个内衬应该是好的,没有任何库:

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

    这使我能够以所需格式获取当前日期(YYYYMMDD HH:MM:SS):

    var d=新日期();
    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());
    打印(日期1+“”+时间1);
    
    var d=新日期(“2014年5月12日太阳”);
    var year=d.getFullYear();
    风险月
    
    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]);
    };
    
    function localDay(time) {
      var minutesOffset = time.getTimezoneOffset()
      var millisecondsOffset = minutesOffset*60*1000
      var local = new Date(time - millisecondsOffset)
      return local.toISOString().substr(0, 10)
    }
    
    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');
    
    var date = new Date("Sun May 11,2014");
    var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                        .toISOString()
                        .split("T")[0];
    
    new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
    
    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);
    
    new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                     (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
    
    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]
    
    date.format(moment.HTML5_FMT.DATE)
    
    (new Date())
        .toISOString()
        .replace(
            /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
            '$<year>-$<month>-$<day>'
        )
    
    (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"
    }
    
    14/7/'20 @ 8:45
    
    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)
    
    .toJSON().slice(0,10);
    
    const formatDate = d => [
        d.getFullYear(),
        (d.getMonth() + 1).toString().padStart(2, '0'),
        d.getDate().toString().padStart(2, '0')
    ].join('-');
    
    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);
    }
    
    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);
    }
    
    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);
    }
    
    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);
    }