如何在JavaScript中获取当前日期?


当前回答

使用JavaScript内置的Date.pr原型.toLocaleDateString()(MDN文档中有更多选项):

常量选项={月份:'2-位',天:'2位数',年份:'数字',};console.log(newDate().toLocaleDateString('en-US',选项));//年/月/日

我们可以使用具有良好浏览器支持的Intl.DateTimeFormat获得类似的行为。与toLocaleDateString()类似,我们可以传递带有选项的对象:

const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'

其他回答

你可以使用我下面给出的DATE API,每天使用日期格式以及获取当前日期、昨天等。如何使用例如

 var dt = new Date();  
       /// ANY DATE YOU WANT --  dt = new Date(""July 21, 1983 01:15:00"")

       dateObj = dt.getFormattedDate();

       alert( dateObj.isToday() );
       alert( dateObj.todayDay() );
       alert( dateObj.monthNameDayYear() );

(function () {

    fnDateProcessor = function () {
        var that = this;

        return {

            yyyymmdd: function (separator) {
                var fdate = this.formatDate(true, true) ,
                    separator = separator ? separator : "-";
                return fdate.year + separator + fdate.month + separator + fdate.day;
            },

            monthNameDayYear: function () {
                var fdate = this.formatDate(true, true);
                return fdate.monthName + " " + fdate.day + ", " + fdate.year;
            },

            ddmmyyyy: function (separator) {
                var fdate = this.formatDate(true, true) ,
                    separator = separator ? separator : "/";
                return fdate.day + separator + fdate.month + separator + fdate.year;
            },

            meridianTime: function () {
                var fdate = this.formatDate();
                return fdate.hour + ":" + fdate.minute + " " + fdate.meridian;
            },

            monthDay: function (separator) {

                var fdate = this.formatDate();
                separator = checkSeparator(separator);
                return fdate.monthName.substring(0, 3) + separator + fdate.day;

            },

            weekMonthDayYear: function () {
                var fdate = this.formatDate();
                //separator = checkSeparator(separator);

                return fdate.weekDay + " " + fdate.monthName.substring(0, 3) +
                    fdate.day + " ," + fdate.year;
            },

            timeZoneInclusive: function () {

                return new Date(that);
            },

            todayDay: function () { return new Date().getDate(); },
            todayMonth: function () { return new Date().getMonth() + 1; },
            dateDay: function () { return this.formatDate().day; },
            dateMonth: function () { return this.formatDate().month; },
            isToday: function () { return this.sameDate(new Date()); },
            isYesterday: function () {
                d = new Date(); d.setDate(d.getDate() - 1);
                return this.sameDate(d);
            },

            formatDate: function () {
                var zeroPaddedMnth = true, zeroPaddedDay = false,
                    zeroPaddedHr = false, zeroPaddedMin = true;
                // Possible to take Options arg that overide / merge to defaults

                var monthNames = [
                    "January", "February", "March",
                    "April", "May", "June", "July",
                    "August", "September", "October",
                    "November", "December"
                ];
                var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

                var day = getFormattedDay(that.getDate(), zeroPaddedDay);
                var monthIndex = that.getMonth();
                var month = getFormattedMonth(monthIndex + 1, zeroPaddedMnth);
                var year = that.getFullYear();
                var wkDay = that.getDay();
                var hour = getFormattedHour(that.getHours(), zeroPaddedHr);
                var minute = getFormattedMinute(that.getMinutes(), zeroPaddedMin);
                var meridian = getMeridian(that.getHours());

                return {
                    "day": day, "monthName": monthNames[monthIndex], "month": month,
                    "weekDay": weekDays[wkDay], "year": year, "hour": hour, "minute": minute,
                    "meridian": meridian
                };
            },

            compareDate: function (d2) {     /// validates if caller is less than argument                            
                d2 = _isString(d2) ? new Date(d2) : d2;

                return !this.sameDate(d2)
                    && typeof d2 != "number"
                    ? that < d2 : false;
            },

            sameDate: function (d) {
                return that.getFullYear() === d.getFullYear()
                    && that.getDate() === d.getDate()
                    && that.getMonth() === d.getMonth();
            },

            dateAfter: function (separator) {
                var fdate = this.formatDate();
                var separator = separator ? separator : "-";
                return fdate.year + separator + fdate.month + separator + (fdate.day + 1);
            }

        };

    };


    function _isString(obj) {
        var toString = Object.prototype.toString;
        return toString.call(obj) == '[object String]';
    }

    function checkSeparator(separator) {
        // NOT GENERIC ... NEEDS REVISION
        switch (separator) {
            case " ": sep = separator; break;
            case ",": sep = " ,"; break;
            default:
                sep = " "; break;
        }

        return sep;
    }

    function getFormattedHour(h, zeroPadded) {
        h = h % 12;
        h = h ? h : 12;    //  12 instead of 00
        return zeroPadded ? addZero(h) : h;
    }

    function getFormattedMinute(m, zeroPadded) {

        return zeroPadded ? addZero(m) : m;
    }

    function getFormattedDay(dd, zeroPadded) {

        return zeroPadded ? addZero(dd) : dd;
    }
    function getFormattedMonth(mm, zeroPadded) {

        return zeroPadded ? addZero(mm) : mm;
    }

    function getMeridian(hr) {

        return hr >= 12 ? 'PM' : 'AM';
    }

    function addZero(i) {
        if (i < 10) {
            i = "0" + i;
        }
        return i;
    }


    Date.prototype.getFormattedDate = fnDateProcessor;

} ());

如果在“当前日期”之前,你正在考虑“今天”,那么这个技巧可能对你有用:

> new Date(3600000*Math.floor(Date.now()/3600000))
2020-05-07T07:00:00.000Z

这样,您将获得时间为0:00:00的日期实例。

操作原理很简单:我们获取当前时间戳,并将其除以1天,以毫秒表示。我们会得到一个分数。通过使用Math.floor,我们去掉了分数,所以我们得到了一个整数。现在,如果我们将它乘以一天(同样是以毫秒为单位),我们会得到一个日期时间戳,时间恰好在一天的开始。

> now = Date.now()
1588837459929
> daysInMs = now/3600000
441343.73886916664
> justDays = Math.floor(daysInMs)
441343
> today = justDays*3600000
1588834800000
> new Date(today)
2020-05-07T07:00:00.000Z

干净简单。

对于任何想要这样的日期格式的人,2020年4月9日

function getDate(){
  var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

  var today = new Date();
  var dd    = String(today.getDate()).padStart(2, '0');
  var mm    = months[today.getMonth()];
  var yyyy  = today.getFullYear();

  today = dd + "-" + mm + "-" + yyyy;
  return today;
}

getDate();

那么多复杂的答案。。。

只需使用new Date(),如果需要它作为字符串,只需使用newDate().toISOString()

享受

var utc=new Date().toJSON().slice(0,10).replace(/-/g,'/');文档.写入(utc);

如果要重用utc变量,例如new Date(utc),请使用替换选项,因为Firefox和Safari无法识别带破折号的日期。