How to get date from a timestamp?

Viewed 430

I have 2 timestamps with different format:

1/2/2021 21:15
19-3-2021 21:15

Is there a method in javascript to get just the date for these timestamps?

Expected output:

'1/2/2021'
'19/3/2021'

I know using substr() is not effective as the length of the date string can vary.

3 Answers

Assuming the two timestamp formats are the only ones to which you need to cater, we can try:

function getDate(input) {
    return input.replace(/\s+\d{1,2}:\d{1,2}$/, "")
                .replace(/-/g, "/");
}

console.log(getDate("1/2/2021 21:15"));
console.log(getDate("19-3-2021 21:15"));

The first regex replacement strips off the trailing time component, and the second replacement replaces dash with forward slash.

  1. Use split() to convert string into array based on space.

  2. Then use replaceAll() on each element of the array, which will replace all the dash(-) which are in dates to slash (/)

  3. Use includes() to check if slash(/) is present or not, as it will separate data(d/m/y) with time(h:m)

function getDateFun(timestamp) {
  let timeStr = timestamp;

  let splitStamp = timeStr.split(" ");
  let dates = [];
  for (let i = 0; i < splitStamp.length; i++) {
    if (splitStamp[i].includes("/") ||        splitStamp[i].includes("-"))
      dates.push(splitStamp[i]);
  }
  console.log(dates.toString());
}

getDateFun("1/2/2021 21:15");
getDateFun("19-3-2021 21:15");
getDateFun("1/2/2021 21:15 19-3-2021 21:15");

Update

Based on RobG comment, the same can be achieved by using Regular Expressions and replace() method.

function getDateFun(timestamp){
return timestamp.split(' ')[0]
                .replace(/\D/g, '/');
}

console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));

function getDateFun(timestamp){
return timestamp
       .replace(/(\d+)\D(\d+)\D(\d+).*/,'$1/$2/$3')
}

console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));

Assuming that your dates have a space character between the date and time you can use the split() method:

let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';

// [0] is the first element of the splitted string
console.log(firstDate.split(" ")[0]); 
console.log(secondDate.split(" ")[0]);

Or you can then also use substr() by first finding the position of the space character:

let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';

let index1 = firstDate.indexOf(' ');
let index2 = secondDate.indexOf(' ');

console.log(firstDate.substr(0, index1)); 
console.log(secondDate.substr(0, index2));

Related