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("/");
Related
I have 2 timestamps with different format:
1/2/2021 21:15
19-3-2021 21:15
Is there a method in javascript to get just the date for these timestamps?
Expected output:
'1/2/2021'
'19/3/2021'
I know using substr() is not effective as the length of the date string can vary.
Assuming the two timestamp formats are the only ones to which you need to cater, we can try:
function getDate(input) {
return input.replace(/\s+\d{1,2}:\d{1,2}$/, "")
.replace(/-/g, "/");
}
console.log(getDate("1/2/2021 21:15"));
console.log(getDate("19-3-2021 21:15"));
The first regex replacement strips off the trailing time component, and the second replacement replaces dash with forward slash.
Use split() to convert string into array based on space.
Then use replaceAll() on each element of the array, which will replace all the dash(-) which are in dates to slash (/)
Use includes() to check if slash(/) is present or not, as it will separate data(d/m/y) with time(h:m)
function getDateFun(timestamp) {
let timeStr = timestamp;
let splitStamp = timeStr.split(" ");
let dates = [];
for (let i = 0; i < splitStamp.length; i++) {
if (splitStamp[i].includes("/") || splitStamp[i].includes("-"))
dates.push(splitStamp[i]);
}
console.log(dates.toString());
}
getDateFun("1/2/2021 21:15");
getDateFun("19-3-2021 21:15");
getDateFun("1/2/2021 21:15 19-3-2021 21:15");
Update
Based on RobG comment, the same can be achieved by using Regular Expressions and replace() method.
function getDateFun(timestamp){
return timestamp.split(' ')[0]
.replace(/\D/g, '/');
}
console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));
function getDateFun(timestamp){
return timestamp
.replace(/(\d+)\D(\d+)\D(\d+).*/,'$1/$2/$3')
}
console.log(getDateFun("28/03/2021 07:50"));
console.log(getDateFun("19-02-2021 15:30"));
Assuming that your dates have a space character between the date and time you can use the split() method:
let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';
// [0] is the first element of the splitted string
console.log(firstDate.split(" ")[0]);
console.log(secondDate.split(" ")[0]);
Or you can then also use substr() by first finding the position of the space character:
let firstDate = '1/2/2021 21:15';
let secondDate = '19-3-2021 21:15';
let index1 = firstDate.indexOf(' ');
let index2 = secondDate.indexOf(' ');
console.log(firstDate.substr(0, index1));
console.log(secondDate.substr(0, index2));
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 can I solve this error, which i keep getting, here it is:
TypeError: date.replace is not a function
date = date.replace("*", "");
And this is all code:
var date = cellElement.innerHTML.split("/");
date = date.replace("*", "");
alert(date);
cellElement.innerHTML looks like this
2015/Rgs/01*
Something is wrong with that replace.
How can I solve it?
Because date is an array, you cannot use string methods on it. When you use split() on string, array is returned.
To replace * symbol from string, you need to first replace it and then split it by /.
var date = cellElement.innerHTML.replace("*", "").split("/");
alert(date);
You are using the wrong type of variable.
method replace works only with type String.
try this:
var date = cellElement.innerHTML.split("/");
var date2string = date.toString();
date = date2string.replace("*", "");
or:
var date = cellElement.innerHTML.replace("*","");
var result = date.split("/");
alert(result);