如何从时间戳中获取日期?

时间:2021-03-26 06:53:42

标签: javascript datetime

我有 2 个不同格式的时间戳:

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

javascript 中是否有一种方法可以仅获取这些时间戳的日期?

预期输出:

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

我知道使用 substr() 无效,因为日期字符串的长度可能会有所不同。

3 个答案:

答案 0 :(得分:3)

假设您只需要满足两种时间戳格式,我们可以尝试:

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

第一个正则表达式替换掉拖尾时间部分,第二个替换用正斜杠替换破折号。

答案 1 :(得分:2)

  1. 使用split()将字符串转换为基于空间的数组。

  2. 然后在数组的每个元素上使用replaceAll(),这将替换日期中的所有破折号(-)以斜线(/)

  3. Use includes() 检查斜线(/) 是否存在,因为它会将数据(d/m/y) 与时间(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");

更新

基于RobG注释,同样可以通过使用Regular Expressionsreplace()方法来实现。

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

答案 2 :(得分:1)

假设您的日期在日期和时间之间有一个空格字符,您可以使用 split() 方法:

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

或者您也可以通过先找到空格字符的位置来使用 substr()

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