Home > database >  javascript date time formatting to build a string
javascript date time formatting to build a string

Time:09-01

needs to be DateString = 20220831142259

Hi I need some help with building a javascript date string using the current date do i need to use .toString on the dateparts to convert the int back? The date format is yyyymmddhhmmss

if the date parts are less than 9 then I want to concatenate a "0" to the string.

//getting the date parts of today 
var year = today().getFullYear().toString();
var month = (today().getMonth()   1).toString();
var day =  today().getDate().toString()
var hours = today().getHours().toString();
var minutes = today().getMinutes().toString();
var seconds = today().getSeconds().toString();


//if the datepart is less than 9 then add a 0 to the beginning
if (int(month) <= "9") {
    int(month) = "0"   int(month);
}
if (int(day) <= "9") {
    int(day) = "0"   int(day);
}

if (int(hours) <= "9") {
    int(hours) = "0"   int(hours);
}

if (int(minutes) <= "9") {
    int(minutes) = "0"   int(minutes);
}

if (int(seconds) <= "9") {
    int(seconds) = "0"   int(seconds);
}

hours = 14
day = 31
minutes = 22
seconds = 59
month = 8

//build full date
DateString = 2022831142259```

CodePudding user response:

Rather than use if statements to assign values like leading zeros, I like to use conditional assignments. Aside from that, you can avoid creating a lot of unneeded variables by just creating 1 date object and then extracting the parts that you need into 1 value.

Here, I have a function that creates a date object based on a date passed in (I am passing the current timestamp in via Date.now(), but you can pass in a date string too if needed). Then it returns the date string in the format you requested using template literals. Leading zeros are applied to the month, date, hour, minute, and second values if they are less than 10 using conditional assignments.

const _DateString = d => {
  let dte = new Date(d);
  return `${dte.getFullYear()}${(dte.getMonth() 1 < 9)?"0" (dte.getMonth() 1):(dte.getMonth() 1)}${(dte.getDate() < 9)?"0" dte.getDate():dte.getDate()}${(dte.getHours() < 9)?"0" dte.getHours():dte.getHours()}${(dte.getMinutes() < 9)?"0" dte.getMinutes():dte.getMinutes()}${(dte.getSeconds() < 9)?"0" dte.getSeconds():dte.getSeconds()}`;
}

console.log(_DateString(Date.now()));

CodePudding user response:

You just have a few issues when trying to work with strings versus numbers to perform the logic you want.

See below for a solution, results in the desired output of the string 20220831142259. Explanation is given below the solution as well.

Solution

const today = new Date();

// if you want to use the current date...
var year = today.getFullYear();
var month = today.getMonth()   1;
var day = today.getDay();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();

// if you want to use sample data...
year = 2022;
hours = 14;
day = 31;
minutes = 22;
seconds = 59;
month = 8;

// format our date parts and convert to strings
year = year.toString();
// if less than or equal to 9, then add a 0 to the beginning...
month = month <= 9 ? "0"   month : month.toString();
day = day <= 9 ? "0"   day : day.toString();
hours = hours <= 9 ? "0"   hours : hours.toString();
minutes = minutes <= 9 ? "0"   minutes : minutes.toString();
seconds = seconds <= 9 ? "0"   seconds : seconds.toString();

console.log(year   month   day   hours   minutes   seconds);
// results in "20220831142259"

https://codesandbox.io/s/manipulate-date-vals-format-string-d18xzr

Explanation

When prefixing numbers 9 and under with a "0", we simply can use the result of getMonth() (or an int assigned per your sample data).

There's no reason to turn the month into a string then back to an integer, as this will add quite a bit of unnecessary work as well as visual noise to the code. We need to work with numbers for doing the conditional logic you require, so we just need the number.

If we need to concatenate our string with prefix "0" for the values 9 or under, we can simply add the integer value to "0" - because we are working with a string "0" our result will be of type string.

If not, we simply convert the value to a string.

Then, we concatenate all the date parts to get the final result.

  • Related