繁体   English   中英

如何以 2 位格式获取 JavaScript 的月份和日期?

[英]How do I get Month and Date of JavaScript in 2 digit format?

当我们在date对象上调用getMonth()getDate()时,我们将得到single digit number 例如 :

对于january ,它显示1 ,但我需要将其显示为01 怎么做?

("0" + this.getDate()).slice(-2)

对于日期,以及类似的:

("0" + (this.getMonth() + 1)).slice(-2)

本月。

如果你想要像“YYYY-MM-DDTHH:mm:ss”这样的格式,那么这可能会更快:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ

或者常用的MySQL日期时间格式“YYYY-MM-DD HH:mm:ss”:

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');

我希望这有帮助

月份示例:

function getMonth(date) {
  var month = date.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}  

您还可以使用此类功能扩展Date对象:

Date.prototype.getMonthFormatted = function() {
  var month = this.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}

为什么不使用padStart

 var dt = new Date(); year = dt.getFullYear(); month = (dt.getMonth() + 1).toString().padStart(2, "0"); day = dt.getDate().toString().padStart(2, "0"); console.log(year + '/' + month + '/' + day);

即使月或日小于 10,这也将始终返回 2 位数字。

笔记:

  • 如果使用babel转译 js 代码,这仅适用于 Internet Explorer。
  • getFullYear()返回 4 位年份,不需要padStart
  • getMonth()返回从 0 到 11 的月份。
    • 在填充前将 1 添加到月份以保持 1 到 12
  • getDate()返回从 1 到 31 的日期。
    • 第 7 天将返回07 ,因此我们不需要在填充字符串之前加 1。

最好的方法是创建自己的简单格式化程序(如下所示):

getDate()返回月份中的第几天(从 1 到 31)
getMonth()返回月份(从 0-11)<从零开始,0=January,11=December
getFullYear()返回年份(四位数)<不要使用getYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}

我会这样做:

 var date = new Date(2000, 0, 9); var str = new Intl.DateTimeFormat('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' }).format(date); console.log(str); // prints "01/09/2000"

以下用于使用三元运算符转换db2日期格式即YYYY-MM-DD

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);
function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}

再举一个例子,几乎是一个班轮。

 var date = new Date(); console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );

如果可以腾出一些时间,我希望得到:

YYYYMMDD

今天,和相处:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');
function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

这是我的解决方案:

function leadingZero(value) {
  if (value < 10) {
    return "0" + value.toString();
  }
  return value.toString();
}

var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;

使用Moment.js可以这样做:

moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month

不是答案,但这是我如何在变量中获得所需的日期格式

function setDateZero(date){
  return date < 10 ? '0' + date : date;
}

var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);

希望这可以帮助!

来自MDN 的提示:

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/

new Date().getMonth()方法以数字形式返回月份 (0-11)

您可以使用此功能轻松获得正确的月份数。

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
function GetDateAndTime(dt) {
  var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());

  for(var i=0;i<arr.length;i++) {
    if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
  }

  return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5]; 
}

这里的答案很有帮助,但我需要的不止这些:对于默认名称,不仅是月份、日期、月份、小时和秒。

有趣的是,尽管上述所有内容都需要在“0”前面加上“+1”,但仅对月份需要“+1”,其他不需要。

例如:

("0" + (d.getMonth() + 1)).slice(-2)     // Note: +1 is needed
("0" + (d.getHours())).slice(-2)         // Note: +1 is not needed

还有另一个版本https://jsfiddle.net/ivos/zcLxo8oy/1/ ,希望有用。

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")

我建议您使用名为 Moment https://momentjs.com/的不同库

这样你就可以直接格式化日期而无需做额外的工作

const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'

确保你也导入了 moment 以便能够使用它。

yarn add moment 
# to add the dependency
import moment from 'moment' 
// import this at the top of the file you want to use it in

希望这有帮助:D

也许更现代的方法,使用“padStart”

const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();

那么您可以根据需要构建为模板字符串:

`${day}/${month}/${year}`

我的解决方案:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

用法:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http : //jsfiddle.net/8xy4Q/1/

var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

如果你想让 getDate() 函数将日期返回为 01 而不是 1,这里是它的代码......让我们假设今天的日期是 01-11-2018

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01

我想做这样的事情,这就是我所做的

ps我知道上面有正确的答案,但只是想在这里添加一些我自己的东西

const todayIs = async () =>{
    const now = new Date();
    var today = now.getFullYear()+'-';
    if(now.getMonth() < 10)
        today += '0'+now.getMonth()+'-';
    else
        today += now.getMonth()+'-';
    if(now.getDay() < 10)
        today += '0'+now.getDay();
    else
        today += now.getDay();
    return today;
}

如果您检查小于 10 ,则不必为此创建新函数。 只需将一个变量分配到括号中并使用三元运算符返回它。

(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},
$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

    var someFormattedDate = year+'-'+month+'-'+day;

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});

日期-fns

import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');

三元运算符解决方案

如果月或日小于 10,简单的三元运算符可以在数字前添加“0”(假设您需要此信息用于字符串)。

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();

怎么容易?

new Date().toLocaleString("en-US", { day: "2-digit" })

其他选项可用,例如:

  • 工作日

更多信息在这里。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options

暂无
暂无

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

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