programing

Javascript는 지금까지 선행 0을 추가했습니다.

copysource 2022. 10. 11. 22:49
반응형

Javascript는 지금까지 선행 0을 추가했습니다.

dd/mm/yyy 형식으로 10일 전에 날짜를 계산하기 위해 이 스크립트를 만들었습니다.

var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();

이러한 규칙을 스크립트에 추가하여 날짜를 일 및 월 구성 요소에 선행 0으로 표시해야 합니다.작동이 안 될 것 같아요.

if (MyDate.getMonth < 10)getMonth = '0' + getMonth;

그리고.

if (MyDate.getDate <10)get.Date = '0' + getDate;

이것들을 스크립트에 삽입하는 장소를 가르쳐 주시면 감사하겠습니다.

http://jsfiddle.net/xA5B7/ 를 사용해 보세요.

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();

편집:

명명 to 。.slice(-2)문자열의 마지막 두 글자를 보여줍니다.

일이 있어도 ''를 붙일 수 요."0"마지막 두 개는 항상 우리가 원하는 것이기 때문에 그냥 마지막 두 개를 물어보세요.

만약에 '만약에'가MyDate.getMonth()9음음음같 뭇매하다

("0" + "9") // Giving us "09"

때문에, 「」를 추가해 주세요..slice(-2)마지막 두 글자는 다음과 같습니다.

("0" + "9").slice(-2)
"09"

, 만약 ★★★★★★★★★★★★★★★★.MyDate.getMonth()10음음음같 뭇매하다

("0" + "10") // Giving us "010"

때문에, 「」를 추가해 주세요..slice(-2)는 마지막 두 글자를 제공합니다.을 사용하다

("0" + "10").slice(-2)
"10"

현대적 방식

이를 위한 새로운 현대적인 방법은 를 사용하는 것입니다.이를 사용하면 적절한 현지화로 날짜를 포맷할 수 있을 뿐만 아니라 포맷 옵션을 전달하여 원하는 결과를 얻을 수 있기 때문입니다.

const date = new Date(2018, 2, 1)
const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

또는 Temporal 객체 사용(아직 제안 중, caniuse):

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const result = date.toLocaleString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

「 」를 사용하는 undefined첫 번째 인수로 브라우저 언어를 검출합니다.외에 '먹다'를 사용할 .2-digit연차 선택도 가능합니다.

성능

많은 날짜 형식을 지정할 계획이라면 대신 다음을 사용하는 것이 좋습니다.

const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
const date = new Date(2018, 2, 1) // can also be a Temporal object
const result = formatter.format(date)
console.log(result) // outputs “01/03/2018”

포맷터는 Date 및 Temporal 객체와 호환됩니다.

과거 날짜

Temporal constructor years는 Temporal constructor years(099년)와 달리 Date constructor에서는 20세기 years로 해석됩니다.이를 방지하려면 다음과 같이 날짜를 초기화하십시오.

const date = new Date()
date.setFullYear(18, 2, 1) // the year is A.D. 18

은 Temporal에서는 모든되는 것은 및 API에 는 것)는 Temporal API 1000을 입니다(Date API Temporal API)4-digit이치노이 경우 수동 포맷을 수행해야 합니다(아래 참조).

ISO 8601 포맷의 경우

YYYY-MM-DD은 다음과 같이

const date = new Date(Date.UTC(2018, 2, 1))
const result = date.toISOString().split('T')[0]
console.log(result) // outputs “2018-03-01”

또는 UTC .toISOString() 하다, 하다, 하다, 하다, 하다를 사용해서 거예요.Date.UTC위와 같이

ISO 8601 형식의 과거 날짜

Temporal constructor years는 Temporal constructor years(099년)와 달리 Date constructor에서는 20세기 years로 해석됩니다.이를 방지하려면 ISO 8601 형식에 사용할 날짜를 다음과 같이 초기화하십시오.

const date = new Date()
date.setUTCFullYear(18, 2, 1) // the year is A.D. 18

1000년 이전 또는 9999년 이후의 날짜를 가진 시간 객체의 ISO 형식은 기존 날짜 API와 비교하여 다릅니다.모든 상황에서 4자리 연도를 적용하기 위해 사용자 지정 포맷으로 폴백하는 것이 좋습니다.

연간 커스텀 4자리 포맷

안타깝게도 포맷터는 그 해의 선두 0을 지원하지 않습니다.4-digit. 이것은 Temporal 객체에 됩니다.이는 시간 객체가 동일한 포맷터를 공유하기 때문에 시간 객체에 대해서도 유지됩니다.

다행히 Date API의 ISO 형식은 항상 최소 4자리 숫자로 표시됩니다.단, Temporal 객체는 표시되지 않습니다.따라서 적어도 Date API의 경우 ISO 8601 형식 방법의 일부를 사용하여 수동 형식 지정 접근방식으로 폴백함으로써 1000년 이전의 과거 날짜를 선행 0으로 포맷할 수 있습니다.

const date = new Date()
date.setUTCFullYear(18, 2, 1)
const ymd = date.toISOString().split('T')[0].split('-')
const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`
console.log(result) // outputs “01/03/0018”

Temporal 객체는 경로를 사용해야 합니다. Temporal 객체는 Temporal 객체로 되기 때문입니다.ISOYearString 1000년 이전과 9999년 이후 날짜의 형식은 이전과 다릅니다.

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const zeroPad = (n, digits) => n.toString().padStart(digits, '0');
const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`;
console.log(result) // outputs “01/03/0018”

여러가지 종류의

Date API와 Temporal API의 경우 날짜의 시간을 현지화하고 형식을 지정할 수도 있습니다.

다음은 Javascript의 Number 프로토타입을 확장하지 않고도 커스텀 "패드" 함수를 사용한 Mozilla Developer Network의 Date 객체 문서의 예입니다.예를 들어 편리한 기능은 다음과 같습니다.

function pad(n){return n<10 ? '0'+n : n}

그리고 아래는 문맥에서 사용되는 것입니다.

/* use a function for the exact format desired... */
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

미래에서 온 여러분을 위해 (ECMAScript 2017 이후)

솔루션

"use strict"

const today = new Date()

const year = today.getFullYear()

const month = `${today.getMonth() + 1}`.padStart(2, "0")

const day = `${today.getDate()}`.padStart(2, "0")

const stringDate = [day, month, year].join("/") // 13/12/2017

설명

가능한 한 많이 추가하다padString String.prototype을 설정합니다.targetLength.

"use strict"

let month = "9"

month = month.padStart(2, "0") // "09"

let byte = "00000100"

byte = byte.padStart(8, "0") // "00000100"

str_pad 함수는 다음과 같이 정의할 수 있습니다(php).

function str_pad(n) {
    return String("00" + n).slice(-2);
}

나는 이것을 할 수 있는 가장 짧은 방법을 찾았다.

 MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');

모든 외로운 한 자리 숫자에 선행 0을 추가합니다.

Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}

//사용 중:

(function(){
 var myDate= new Date(), myDateString;
 myDate.setDate(myDate.getDate()+10);

 myDateString= [myDate.getDate().padZero(),
 (myDate.getMonth()+1).padZero(),
 myDate.getFullYear()].join('/');

 alert(myDateString);
})()

/*  value: (String)
09/09/2010
*/
var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();

또 방법이 .sliceJavaScript에 있습니다.

var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);

datestring원하는 형식으로 반환 날짜: 2019-09-01

또 다른 접근법은dateformat라이브러리: https://github.com/felixge/node-dateformat

3진 연산자를 사용하여 "if" 문과 같은 날짜 형식을 지정할 수 있습니다.

예를 들어 다음과 같습니다.

var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();

그렇게

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

getDate()가 10보다 작은 값을 반환하는 경우 '0' + 날짜를 반환하거나 10보다 큰 경우 날짜를 반환하는 if 문과 비슷합니다(선행 0을 추가할 필요가 없기 때문에).이번 달도 똑같아요.

편집: get Month가 0으로 시작하는 것을 잊어버렸기 때문에 +1을 추가했습니다.물론 d.get Month() < 9 : 라고도 할 수 있습니다만, +1 을 사용하면 알기 쉬워질 것 같습니다.

최근에는 String.protype.padStart를 사용하여 쉽고 빠르게 목표를 달성할 수도 있습니다.

String(new Date().getMonth() + 1).padStart(2, '0')

가용성은 caniuse에서 평가할 수 있습니다.

var date = new Date()

var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')

console.log('%s/%s/%s', month, day, year)

확인.

var date = new Date('7/4/2021')
    
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
    
/**
 * Expected output: 07/04/2021
 */
console.log('%s/%s/%s', month, day, year)

이전 브라우저용 폴리필

String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
    configurable : true,
    writable : true,
    value : function (targetLength, padString) {
        'use strict'
        /**
         * String.prototype.padStart polyfill
         * https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
         */
        targetLength = targetLength | 0
        padString = arguments.length > 1 ? String(padString) : ' '

        if (this.length < targetLength && padString.length) {
            targetLength = targetLength - this.length

            while (padString.length < targetLength) {
                padString += padString
            }

            return padString.slice(0, targetLength) + this
        } else {
            return this
        }
    }
})
function formatDate(jsDate){
  // add leading zeroes to jsDate when days or months are < 10.. 
  // i.e.
  //     formatDate(new Date("1/3/2013")); 
  // returns
  //    "01/03/2103"
  ////////////////////
  return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
      ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
      jsDate.getFullYear();
}

날짜 형식을 지정하는 매개 변수로 옵션을 제공할 수 있습니다.첫 번째 파라미터는 필요하지 않을 수 있는 로케일용이고 두 번째 파라미터는 옵션용입니다.상세한 것에 대하여는, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString 를 참조해 주세요.

var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));

이 질문의 정답은 선행 0을 여러 개 추가할 수 있지만 기본적으로는 0을 1개 추가하는 함수로 포장했습니다.

function zeroFill(nr, depth){
  depth = (depth === undefined)? 1 : depth;

  var zero = "0";
  for (var i = 0; i < depth; ++i) {
    zero += "0";
  }

  return (zero + nr).slice(-(depth + 1));
}

2자리 이하의 숫자로만 작업하는 경우에도 이 방법이 있습니다.

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

또 다른 옵션은 내장 함수를 사용하여 패딩을 수행하는 것입니다(그러나 상당히 긴 코드 발생).

myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + myDate.getFullYear();

// '12/06/2017'

또 다른 정규 표현으로 문자열을 조작합니다.

var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');

// '2017/06/12'

단, 1년은 시작일, 끝일은 종료일이라는 점에 유의해 주십시오.

@modiX의 답변에 덧붙여 다음과 같이 동작합니다.빈칸으로 두지 마십시오.

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})

다음과 같은 커스텀 날짜 도우미를 만듭니다.

var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

( 바이올린도 참조)

@John Henckel이 제안하듯이 toISOString() 메서드를 사용하면 작업이 쉬워집니다.

const dateString = new Date().toISOString().split('-');
const year = dateString[0];
const month = dateString[1];
const day = dateString[2].split('T')[0];

console.log(`${year}-${month}-${day}`);

기본 기능으로 사용해 보십시오. 라이브러리는 필요 없습니다.

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};

이 상황을 어떻게 처리할 수 있는지 매우 간단한 예를 다음에 제시하겠습니다.

var mydate = new Date();

var month = (mydate.getMonth().toString().length < 2 ? "0"+mydate.getMonth().toString() :mydate.getMonth());

var date = (mydate.getDate().toString().length < 2 ? "0"+mydate.getDate().toString() :mydate.getDate());

var year = mydate.getFullYear();

console.log("Format Y-m-d : ",year+"-"+month+"-" + date);

console.log("Format Y/m/d : ",year+"/"+month+"/" + date);

다음과 같이 간단하게 사용할 수 있습니다.

const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

따라서 다음과 같은 함수를 만들 수 있습니다.

AddZero(val){
    // adding 0 if the value is a single digit
    return `0${val}`.slice(-2);
}

새 코드:

var MyDate = new Date();
var MyDateString = new Date();

MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();

toISOString은 선행0 을 얻을 수 있습니다.

    const currentdate = new Date(); 
    const date = new Date(Date.UTC(currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
    //you can pass YY, MM, DD //op: 2018-03-01
    //i have passed YY, MM, DD, HH, Min, Sec // op : 2021-06-09T12:14:27.000Z
    console.log(date.toISOString());

출력은 2021-06-09T12:14:27.000Z와 비슷합니다.

이 솔루션이 더 쉽고 기억하기 쉽다고 생각합니다.

var MyDate = new Date();


var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();

day = checkDate(day);
month = checkDate(month);


function checkDate(i){
    if(i < 10){
    i = '0' + i;
  }
  return i;
}

console.log(`${month}/${day}/${year}`);

const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;

은 구성을 을 목표로 하고 , 음음음음음음음음음음음음음음음음음음 the the the the the the the the the the the the the the the the the the the the the the the the the the.Date.protoype설정을 적용합니다.

사용하였습니다.Array, 내가 시간 청크를 저장했을 때,push() thisDate오브젝트, 반복할 길이를 반환합니다.'먹다', '먹다', '먹다' 쓸 수 있어요.join returndiscloss.discloss 。

이것은 매우 빠르게 동작하는 것 같다: 0.016ms

// Date protoype
Date.prototype.formatTime = function (options) {
    var i = 0,
        time = [],
        len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());

    for (; i < len; i += 1) {
        var tick = time[i];
        time[i] = tick < 10 ? options.pad + tick : tick;
    }

    return time.join(options.separator);
};

// Setup output
var cfg = {
    fieldClock: "#fieldClock",
    options: {
        pad: "0",
        separator: ":",
        tick: 1000
    }
};

// Define functionality
function startTime() {
    var clock = $(cfg.fieldClock),
        now = new Date().formatTime(cfg.options);

    clock.val(now);
    setTimeout(startTime, cfg.options.tick);
}

// Run once
startTime();

데모: http://jsfiddle.net/tive/U4MZ3/

필요한 경우 선행 0을 허용하는 패딩을 추가하고 선택한 구분 기호를 문자열로 사용하여 연결합니다.

Number.prototype.padLeft = function(base,chr){
        var  len = (String(base || 10).length - String(this).length)+1;
        return len > 0? new Array(len).join(chr || '0')+this : this;
    }

var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
 let date = new Date();
 let dd = date.getDate();//day of month

 let mm = date.getMonth();// month
 let yyyy = date.getFullYear();//day of week
 if (dd < 10) {//if less then 10 add a leading zero
     dd = "0" + dd;
   }
 if (mm < 10) {
    mm = "0" + mm;//if less then 10 add a leading zero
  }
function pad(value) {
    return value.tostring().padstart(2, 0);
}

let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);

String을 사용할 수 있습니다.slice(): 문자열의 섹션을 추출하여 원래 문자열을 변경하지 않고 새 문자열로 반환합니다.

const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16

또는 Moment.js와 같은 lib를 사용하여 날짜 형식을 지정할 수도 있습니다.

const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16

간단한 날짜 형식 라이브러리가 내 생명을 구했습니다(GitHub):

  • Node.js:var dateFormat = require("dateformat");
  • ES6:import dateFormat from "dateformat";
const now = new Date();             // consider 3rd of December 1993

const full = dateFormat(today, "yyyy-mm-dd");  // 1993-12-03
const day = dateFormat(today, "dd");           // 03
const month = dateFormat(today, "mm");         // 12
const year = dateFormat(today, "yyyy");        // 1993

다양한 마스크 옵션을 지원합니다.

언급URL : https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date

반응형