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();
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.
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.
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);
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"
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With