Как получить текущую дату в JavaScript? - PullRequest
1993 голосов
/ 07 октября 2009

Как мне получить текущую дату в JavaScript?

Ответы [ 44 ]

2 голосов
/ 08 января 2019

Если вы хотите отформатировать в строку.

statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();

вывод "время 11:30:53"

2 голосов
/ 06 ноября 2018

Если вы ищете более детальный контроль над форматами даты, я настоятельно рекомендую проверить дату-FNS. Потрясающая библиотека - намного меньше, чем moment.js, и ее функциональный подход делает ее намного быстрее, чем другие библиотеки на основе классов. Обеспечить большое количество операций, необходимых по датам.

https://date -fns.org / документы / Getting Started-

2 голосов
/ 01 июня 2015

Довольно распечатать дату, как это.

1 июня 2015 г. 11:36:48

https://gist.github.com/Gerst20051/7d72693f722bbb0f6b58

2 голосов
/ 04 мая 2016

2,39 КБ минимизировано. Один файл. https://github.com/rhroyston/clock-js

Просто пытаюсь помочь ...

enter image description here

1 голос
/ 23 января 2019

Этот ответ предназначен для людей, которые ищут дату в формате, подобном ISO-8601, и с часовым поясом. Это чистый JS для тех, кто не хочет включать какую-либо библиотеку дат.

      var date = new Date();
      var timeZone = date.toString();
      //Get timezone ( 'GMT+0200' )
      var timeZoneIndex = timeZone.indexOf('GMT');
      //Cut optional string after timezone ( '(heure de Paris)' )
      var optionalTimeZoneIndex = timeZone.indexOf('(');
      if(optionalTimeZoneIndex != -1){
          timeZone = timeZone.substring(timeZoneIndex, optionalTimeZoneIndex);
      }
      else{
          timeZone = timeZone.substring(timeZoneIndex);
      }
      //Get date with JSON format ( '2019-01-23T16:28:27.000Z' )
      var formattedDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
      //Cut ms
      formattedDate = formattedDate.substring(0,formattedDate.indexOf('.'));
      //Add timezone
      formattedDate = formattedDate + ' ' + timeZone;
      console.log(formattedDate);

Напечатайте что-то вроде этого в консоли:

2019-01-23T17: 12: 52 GMT + 0100

JSFiddle: https://jsfiddle.net/n9mszhjc/4/

1 голос
/ 04 октября 2018

Я думал, что вставлю то, что я использую для реальной даты:

function realDate(date){
    return date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getUTCFullYear();
}

var ourdate = realDate(new Date);
1 голос
/ 22 апреля 2014
(function() { var d = new Date(); return new Date(d - d % 86400000); })()
1 голос
/ 10 февраля 2015

Это мой текущий фаворит, потому что он гибкий и модульный. Это коллекция из (как минимум) трех простых функций:

/**
 * Returns an array with date / time information
 * Starts with year at index 0 up to index 6 for milliseconds
 * 
 * @param {Date} date   date object. If falsy, will take current time.
 * @returns {[]}
 */
getDateArray = function(date) {
    date = date || new Date();
    return [
        date.getFullYear(),
        exports.pad(date.getMonth()+1, 2),
        exports.pad(date.getDate(), 2),
        exports.pad(date.getHours(), 2),
        exports.pad(date.getMinutes(), 2),
        exports.pad(date.getSeconds(), 2),
        exports.pad(date.getMilliseconds(), 2)
    ];
};

Вот функция пэда:

 /**
 * Pad a number with n digits
 *
 * @param {number} number   number to pad
 * @param {number} digits   number of total digits
 * @returns {string}
 */
exports.pad = function pad(number, digits) {
    return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};

Наконец, я могу либо построить строку даты вручную, либо использовать простые функции, чтобы сделать это для меня:

/**
 * Returns nicely formatted date-time
 * @example 2015-02-10 16:01:12
 *
 * @param {object} date
 * @returns {string}
 */
exports.niceDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5];
};

/**
 * Returns a formatted date-time, optimized for machines
 * @example 2015-02-10_16-00-08
 *
 * @param {object} date
 * @returns {string}
 */
exports.roboDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5];
};
1 голос
/ 12 декабря 2017

Это может помочь вам

let d = new Date();                      

this.dateField = element(by.xpath('xpath here'));
this.datetField.sendKeys((d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear());
1 голос
/ 16 мая 2015

Попробуйте это .. HTML

<p id="date"></p>

JS

<script>
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.getElementById("date").innerHTML =("<b>" + day + "/" + month + "/" + year + "</b>")
</script>

Рабочая демоверсия на текущую дату

Демо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...