如何从Javascript日期获取年份的最后2位数字

Vyt*_*alo 4 javascript string format formatting date

我有以下格式的字符串“30.11.2019”。我需要将其转换为日期并获得短年份表示(年份的最后 2 位数字),如“19”。以下代码不起作用

var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear(); 
Run Code Online (Sandbox Code Playgroud)

luk*_*ups 8

我不完全确定您是否只想要年份或整个日期的简短表示,但需要年份的简短表示 - 如果是这样,那么我建议使用toLocaleDateString方法:

new Date(2019, 10, 30).toLocaleDateString('pl', {day: 'numeric', month: 'numeric', year: '2-digit'})
Run Code Online (Sandbox Code Playgroud)

它会返回给你:

"30.11.19"
Run Code Online (Sandbox Code Playgroud)

或者如果您只想获取短年份日期:

new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})
Run Code Online (Sandbox Code Playgroud)

它会返回给你:

"19"
Run Code Online (Sandbox Code Playgroud)


Dra*_*scu 5

new Date() 不适用于该格式的单个字符串参数。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

最简单的方法是用 3 个参数(年、月、日)调用它。请注意,这month是月份索引(基于 0),因此 11 月(第 11 个月)实际上是 Date 期望的格式的第 10 天。

  new Date(2019, 10, 30).getFullYear() % 100;
  // returns 19;
Run Code Online (Sandbox Code Playgroud)

如果你不能这样做,你只需要解决提到的字符串格式,那么你可以这样做

const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);
Run Code Online (Sandbox Code Playgroud)


Ste*_*ski 3

您可以使用以下代码获取最后两位数字:

var strDate = new Date(); // By default Date empty constructor give you Date.now
var shortYear = strDate.getFullYear(); 
// Add this line
var twoDigitYear = shortYear.toString().substr(-2);
Run Code Online (Sandbox Code Playgroud)