Reputation: 3324
I'm making use of the datepicker from Element Ui where the user can select a range in dates. When the user fills in the datepicker, this is what I get back: ['2018-01', '2019-02']
. So just an array with two String elements. NOT a Date()
object.
When dynamically outputting this to the user, I would like to show it as: January 2018 - February 2019
I got it somewhat working in my project but the code just really sucks and also doesn't work properly either. Checkout this gif of my current project and somewhat desired result. I was wondering if someone knows a good and easy way of achieving my desired result without too much hassle. I cannot use methods like toLocaleDateString()
because it isn't a Date()
object. I've got my code working in a Codesandbox. If any if you guys knows a solution feel free to edit the listed Codesandbox, I would highly highly appreciate it!
In the Codesandbox I got a computed property formateDate
. The basic idea of the computed property is to cut the elements of the array I get back from the datepicker
before and after the -
effectively giving me the first & second month and first & second year. That data I store in these variables:
let monthOne;
let monthTwo;
let yearOne;
let yearTwo;
Since I get the months back as '01'
and '02'
for example, I created an array of objects to transform the '01'
and '02'
to January
and February
with a for loop. I then store the result in a new variable with:
displayDate = monthOne + ' ' + yearOne + ' - ' + monthTwo + ' ' + yearTwo;
Lastly, I tried to store that result into the timeperiodDisplayString
at the correct index in the experience
array of objects. Anyway, I'm probably overcomplicating this way to hard so I would REALLY appreciate any help with this.
Upvotes: 0
Views: 2756
Reputation: 509
You can use parse() function from javascript.
var d = Date.parse("2019-01");
console.log(new Date(d));
Upvotes: 0
Reputation: 249
Maybe you could map over the result from the datepicker component to create an array of Date objects. So you can use toLocaleDateString()
Something like this should work:
['2018-01', '2019-02'].map((date) => {
const split = date.split('-');
return new Date(split[0], +split[1] - 1);
});
Upvotes: 1