programing

자바스크립트의 월과 날짜를 2자리 형식으로 가져오려면 어떻게 해야 하나요?

randomtip 2022. 11. 21. 22:56
반응형

자바스크립트의 월과 날짜를 2자리 형식으로 가져오려면 어떻게 해야 하나요?

할 때getMonth() ★★★★★★★★★★★★★★★★★」getDate()date오브젝트, 우리는 그것을 얻을 것이다.single digit number예를 들어 다음과 같습니다.

★★★의 january 라고됩니다.101떻게게 하???

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

날짜 및 유사:

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

한 달 동안.

「YYY-MM-DDTHH:mm:ss」와 같은 포맷을 사용하고 싶은 경우는, 이 포맷이 보다 빠를 수 있습니다.

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

또는 일반적으로 사용되는 MySQL datetime 형식 "YYY-MM-DD HH:mm:ss":

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

이게 도움이 됐으면 좋겠다

왜 사용하지 않는가?

padStart(targetLength, padString)

  • targetLength2
  • padString0

// Source: https://stackoverflow.com/a/50769505/2965993

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자리 숫자가 반환됩니다.

주의:

  • 이 기능은 js 코드가 babel을 사용하여 변환된 경우에만 Internet Explorer에서 작동합니다.
  • getFullYear() 4자리 숫자를 반환하며 필요 없습니다.padStart.
  • getMonth() 0 ~ 11 의 월을 반환합니다.
    • 패딩 전 달에 1을 추가하여 1에서 12까지 유지합니다.
  • getDate() 1 ~ 31 의 날짜를 반환합니다.
    • 07스트링을 채우기 전에 1을 추가할 필요가 없습니다.

월의 예:

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
}

이를 위한 가장 좋은 방법은 다음과 같이 사용자 고유의 간단한 포맷터를 작성하는 것입니다.

getDate()1~31을 합니다.
getMonth()월(0~11) <제로 베이스, 0=1월, 11=12월)을 반환합니다.
getFullYear()년(4자리) < 사용하지 않음

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"

다음은 3진 연산자를 사용하여 db2 날짜 형식(예: YYY-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);

또 다른 예로, 거의 하나의 라이너입니다.

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

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

제가 찾고 있던 시간이 좀 있다면:

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

이게 도움이 됐으면 좋겠네요!

const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD

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}`

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

나는 당신이 Moment https://momentjs.com/라는 다른 라이브러리를 사용할 것을 제안합니다.

이렇게 하면 추가 작업을 하지 않고도 날짜 형식을 직접 지정할 수 있습니다.

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

사용할 수 있도록 모멘트를 Import 하는 것도 잊지 마세요.

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

삼원 오퍼레이터 솔루션

단순한 3진 연산자는 월 또는 날이 10보다 작을 경우 숫자 앞에 "0"을 추가할 수 있습니다(문자열에서 사용하기 위해 이 정보가 필요한 경우).

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
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]; 
}

또한 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")

이 답변은 도움이 됩니다.단, 기본 이름의 월, 날짜, 월, 시간 및 초뿐만 아니라 그 이상의 답변이 필요합니다.

흥미롭게도 "0"의 앞부분은 모두 필요했지만 "+1"은 다른 부분이 아닌 한 달 동안만 필요했습니다.

예:

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

얼마나 쉬워요?

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

다음과 같은 다른 옵션을 사용할 수 있습니다.

  • 평일
  • 연도

자세한 것은 이쪽.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options

솔루션:

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() 함수가 날짜를 1이 아닌 01로 되돌리도록 하려면 다음 코드를 사용합니다.오늘이 2018년 1월 11일이라고 가정합니다.

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

이런 걸 해보고 싶었고 이렇게 했어요.

p.s. 위에 정답이 있다는 것을 알지만, 여기에 나만의 것을 추가하고 싶었다.

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보다 작으면 새로운 기능을 만들 필요가 없습니다.괄호 안에 변수를 할당하고 3진 연산자와 함께 반환하기만 하면 됩니다.

(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;
},

언급URL : https://stackoverflow.com/questions/6040515/how-do-i-get-month-and-date-of-javascript-in-2-digit-format

반응형