Home > Enterprise >  How to handle all missing leading zeros case in datetime strings in javascript?
How to handle all missing leading zeros case in datetime strings in javascript?

Time:08-03

function convertDate(date: any) {
    
    if(typeof date == 'string') {
        date = new Date(date).toISOString()
    }
    console.log('new')
    console.log(date)

    if (props.isUTC) {
        return date.utc(true).toISOString()
    }

    return date.toISOString()
}

I need to write a date function that accepts any string and outputs at the end a datetime in this format: yyyy-mm-dd HH:mm

The issue is that the above function throws an error when we send something without a leading zero. Is there a way to fix it easily?

2022-08-03 03:55 //this works
2022-08-03 3:55 //this doesn't work
2022-08-3 03:55 //this doesn't work

I did try with something like this:

if (!date.isValid()) {

    let day = date.getDate()
    let month = date.getMonth()   1
    const year = date.getFullYear()
    let hour =  date.getHours()
    let minute =  date.getMinutes()
    let second =  date.getSeconds()

    if (month.toString().length < 2) month = '0'   month
    if (hour.toString().length < 2) hour = '0'   hour
    if (day.toString().length < 2) day = '0'   day
    if (minute.toString().length < 2) minute = '0'   minute
    if (second.toString().length < 2) second = '0'   second
    console.log('invalid')
    
    date = new Date(year   '-'   month   '-'   day   ' '   hour   ':'   minute   ':'   second)
    console.log(date)
}

But it didn't work.

CodePudding user response:

You can split and join, padding each string with 0 until length of 2 using String.padStart()

console.log(fixDateTime("2022-08-03 3:55"));
console.log(fixDateTime("2022-8-3 3:55"));

function pad2(str, sepa) {
  var arr = str.split(sepa);
  arr = arr.map(item => (""   item).padStart(2, '0'));
  str = arr.join(sepa);
  return str;
}

function fixDateTime(str) {
  var arr = str.split(/\s /);
  var result = pad2(arr[0], '-')   " "   pad2(arr[1], ':');
  return result;
}

CodePudding user response:

You can format the date using the internationalization api like bellow :

function convertDate(date){
  const newDate = new Date(date);
  if(!newDate) return console.log('Invalid input');

  const options = {
     year: 'numeric',
     month: '2-digit',
     day: '2-digit',
     hour: '2-digit',
     minute: '2-digit', 
  };

  // Using the internationalization api (Intl)
  // syntx: Intl.DateTimeFormat(locale, options).format(value);
  // locale is the langue code. eg. ('en-GB' for Great Britain English) 
  // option is an object with the formatting options as above.
 // value is the value to be formated.


  return Intl.DateTimeFormat('en-US', options).format(newDate);  
}

// Note: you can use the Intl api to format numbers, currencies... you can check it out here for more info.

  • Related