I'm trying to insert events into a calendar. the problem is my events are structured like this: xx/xx/xxxx and the calendar uses another format
xx-xx-xxxx. How do I make this transformation ?
I have transformed the dates from JSON format to a string but I can't change the / into -.
data.forEach(function (element) {
let date = new Date(element.sessionDate)
datesArr.push(date.toLocaleDateString())
})
console.log(datesArr)
And now my array looks like this:
0: "12/24/2018"
1: "12/27/2018"
2: "1/3/2019"
3: "1/3/2019"
4: "1/7/2019"
My expected result for the calendar to receive the events should be: ['2019-03-04', '2019-03-08', '2019-03-12', '2019-03-15'].
There are a couple of ways to do this:
The array version
You could replace them using a regex and then glue matched values back together.
const input = '12/24/2018';
const parts = input.split('/');
const output = `${parts[2]}-${parts[0]}-${parts[1]}`;
console.log(new Date(output));
The regex version
You could replace them using a regex and then glue matched values back together.
const input = '12/24/2018';
const output = input.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, '$3-$1-$2');
console.log(new Date(output));
Or using a library like moment.js
Split the string value by "/" separation gives an array of results. Then join the array with "-" to get the string result back. Use Array.map() to transform into a new array.
const dates = ['2019/03/04', '2019/03/08', '2019/03/12', '2019/03/15'];
const formattedDates = dates.map( date => date.split("/").join("-"));
console.log(formattedDates); //["2019-03-04", "2019-03-08", "2019-03-12", "2019-03-15"]
Related
Why cant i convert this arr
let stringarr = "[2022/07/12, 2022/08/09]"
to this arr
let arr = JSON.parse(stringarr) ---> error
Unexpected token / in JSON at position 5
It's not valid JSON, since the array elements aren't quoted.
If the array elements are all dates formatted like that, you could use a regular expression to extract them.
let stringarr = "[2022/07/12, 2022/08/09]"
let dates = stringarr.match(/\d{4}\/\d{2}\/\d{2}/g);
console.log(dates);
what can i do then to convert it to an array
There are several ways to do that, if the format of the string stays like this. Here's an idea.
console.log(`[2022/07/12, 2022/08/09]`
.slice(1, -1)
.split(`, `));
Or edit to create a valid JSON string:
const dateArray = JSON.parse(
`[2022/07/12, 2022/08/09]`
.replace(/\[/, `["`)
.replace(/\]/, `"]`)
.replace(/, /g, `", "`));
console.log(dateArray);
Or indeed use the match method #Barmar supplied.
const regexp = /\d+\/\d+\/\d+/g;
const stringarr = "[2022/07/12, 2022/08/09]";
const arr = [...stringarr.matchAll(regexp)];
console.log(arr)
It's to much simple 😄.
As your input is a valid array in string format. So, remove [ ] brackets and split with comma (,). Then it automatically generates an array.
let stringarr = "[2022/07/12, 2022/08/09]";
let arr = stringarr.replace(/(\[|\])/g, '').split(',');
Output:
['2022/07/12', ' 2022/08/09']
I have this object "FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020" and need to extract the FROM_DATE value 2/9/2020. I am trying to use replace, to replace everything before and after the from date with an empty string, but I'm not sure how to get both sides of the value.
at the moment I can remove everything up until the date value with this... /.*FROM_DATE":"/ but how can I now remove the final part of the object?
Thanks
If you need to make it with replace, just use:
const input = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
const date = input.replace(/^.*"FROM_DATE":"([\d/]+)".*$/, '$1');
Now you can use date with just the date in it...
In a second time you could remove /",.*/, but this seems too much heuristic to me.
You'd better just catch the first capturing group from the following regex:
/FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
let str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
let pattern = /FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
alert(str.match(pattern)[1]);
Your sample string looks very much like JSON. So much so in fact that you could just wrap it in braces, parse it as and object, and get the value of the FROM_DATE.
EG:
function almostJsonStringToObject(str) {
return JSON.parse('{' + str + '}');
}
var str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
var obj = almostJsonStringToObject(str);
var fromdate = obj.FROM_DATE;
console.log(fromdate);
I have an array of object that I need to iterate through. I'm trying to check that is contain the following string date : "7/2/2019 - 7/31/2019".
My issue is that my regex is not working :
const dateType = /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/;
I tried to filter trough this array of objects and check with a regex that current object.name string contain said string date but as before, my regex is problematic.
const isMatch = this.state.selectedFilters.filter((filter) =>
dateType.test(filter.name));
if (isMatch) {
// ...
}
How to make my regex match this format of dates : "7/2/2019 - 7/31/2019"?
Thanks in advance for your help.
Try this:
((0?[1-9])|(1[0-2]))\/((0?[1-9])|([12][0-9])|(3[01]))\/((\d{4})|(\d{2}))\s*-\s*((0?[1-9])|(1[0-2]))\/((0?[1-9])|([12][0-9])|(3[01]))\/((\d{4})|(\d{2}))
Here Is Demo
Here is a regex that will work : ^(((0)[0-9])|((1)[0-2]))(\/)([0-2][0-9]|(3)[0-1])(\/)\d{4} - (((0)[0-9])|((1)[0-2]))(\/)([0-2][0-9]|(3)[0-1])(\/)\d{4}$
The format is mm/dd/yyy - mm/dd/yyy.
You can use moment library to determine whether this date range is valid or not.
For example:
let dateRange = "7/2/2019 - 7/31/2019";
let start = dateRange.split('-')[0];
let end = dateRange.split('-')[1];
moment(start).isValid(); // true
moment(end).isValid(); // true
you can combine it with your desired date format like so:
moment('17/23/2019').format("M/D/YYYY"); // print invalid date
I have string date like
'new Date(0,0,0,11,13,16)'
and want to change it to
new Date(0,0,0,11,13,16)
anyone have an idea on it.
thanks
var str = 'new Date(0,0,0,11,13,16)';
var str1 = str.match(/\(.*\)/g)[0];
str1 = str1.replace('(', '');
str1 = str1.replace(')', '');
var dateArr = str1.split(',');
var updatedDate = new
Date(dateArr[0],dateArr[1],dateArr[2],dateArr[3],dateArr[4],dateArr[5]);
console.log(updatedDate);
Use regex to solve this problem by matching only numbers. match will return an array of numbers so use the spread operator to set all the parameters to Date.
const res = new Date(...'new Date(0,0,0,11,13,16)'.match(/[0-9]+/g));
console.log(res);
Theoretically you could use the eval function for that.
Depending on the use, this does propose some security risk though. Read more about this here
If it's possible I would suggest you use another form of date string, e.g. "yyyy-mm-dd" (2019-02-17) and parse it to a date object using the new Date(dateString) constructor (new Date('2019-01-17')).
how to split an array index i.e.. sample code
var parts = currentVal.split(" ");
var datePart = parts.splice(0,1);
alert("Date: " + datePart );
var timePart = parts.join(' ');
here i am validating the date time regular expression. var datePart is an array index, now i want to split datepart ....
var parts1 = datePart.split('/');
parts1.date = parseInt(parts1[0]);
parts1.month = parseInt(parts1[1]);
parts1.year = parseInt(parts1[2]);
but it is showing uncaught type error, their is no method split(); Can any one help me how do i separate date, month, year.
If you're trying to just check whether a string represents a valid date or not, I would personally recommend the magical Date object that javascript natively supports. Through some sort of wizardry it can read the date in almost any format you throw at it, and if it is an invalid date it will evaluate to the string Invalid Date.
So to check if currentVal is a valid date, do:
if (new Date(currentVal) == 'Invalid Date') {
... // The date is invalid
} else {
... // The date is valid
}
On the other hand, if you need to use a specific regex to validate the date, you could either do something like
var parts = currentVal.split(' ');
var dateParts = parts[0].split('/');
var timePart = parts[1]; // Maybe you want to split this as well?
And this would leave dateParts as an array containing the month, day and year.
I think you are looking for the function explode().
http://php.net/manual/en/function.explode.php
Actually function splice returns an array of removed elements, so to solve you problem you just need to apply split on the first element of datePart array:
var parts1 = datePart[0].split("/");