Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last 2 digits of year from Javascript date [duplicate]

I have string in the following format "30.11.2019". I need to transform it into a Date and get the short year representation (last 2 digits from year) like "19". The following code doesn't work

var strDate = new Date("30.11.2019");
var shortYear = strDate.getFullYear(); 
like image 200
Vytsalo Avatar asked Nov 29 '19 08:11

Vytsalo


People also ask

How do I get month and date of JavaScript in 2 digit format?

Use the getMonth() method to get the month for the given date. Use the getDate() method to get the day of the month for the given date. Use the padStart() method to get the values in a 2-digit format.

What is date () JavaScript?

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.


4 Answers

new Date() does not work with a single string argument in that format. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Easiest way is to call it with 3 arguments (year, month, day). Do note that month is the month index (0 based), so November (11th month) is actually 10th in the format that Date expects.

  new Date(2019, 10, 30).getFullYear() % 100;
  // returns 19;

If you can't do it this way and you simply must work around the string format mentioned, then you can just do

const dateString = '30.11.2019';
const year = dateString.substring(dateString.length-2);
like image 134
bamtheboozle Avatar answered Oct 22 '22 03:10

bamtheboozle


I'm not entirely sure if you want only short representation of the year or whole date, BUT with short representation of the year on it - if so, then I would suggest using toLocaleDateString method:

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

It will return you:

"30.11.19"

or if you want to get the short year date only:

new Date(2019, 10, 30).toLocaleDateString('en', {year: '2-digit'})

it will return you:

"19"
like image 36
lukaszkups Avatar answered Oct 22 '22 04:10

lukaszkups


You can get last two digits with the following code:

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);
like image 3
Stefan Popovski Avatar answered Oct 22 '22 03:10

Stefan Popovski


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.

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.

like image 1
Giant Robot Avatar answered Oct 22 '22 03:10

Giant Robot