Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - 如何从Javascript日期获取年份的后两位数字(How to get last 2 digits of year from Javascript date [duplicate])

I have string in the following format "30.11.2019".(我有以下格式的字符串“ 30.11.2019”。)

I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19".(我需要将其转换为Date并获得像“ 19”之类的短年份表示形式(年份的最后2位数字)。) The following code doesn't work(以下代码不起作用)
var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear(); 
  ask by Vytsalo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since the string you're using isn't in a format recognized by Date.parse() (more on that here ), you need to manually create that Date object.(由于您使用的字符串不是被识别的格式Date.parse() (更多的在这里 ),您需要手动创建一个Date对象。)

For example:(例如:)

 const strDate = '30.11.2019'; let [d,m,y] = strDate.split(/\D/); const date = new Date(y, --m, d); console.log(date.getFullYear()) 

You can then use Date.getFullYear() to get the year and extract the last two digits, as you need.(然后,您可以根据需要使用Date.getFullYear()获取年份并提取最后两位数字。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...