Javascript- how can i extract datetime from this ajax responsetext:
This text was brought to you by AJAX
Your request was received at:
Sunday 11 November 2018, 02:40:00 am
I would use a regex to accomplish this. The regex:
/\w{3,6}day.*(?:am|pm)$/i
It starts by matching 3 or 4 Word chars, followed by 'day', then matches any number of any char until it reaches either 'am' or 'pm' and end of string. It uses the case inssensitive match.
How to use:
var text = 'This text was brought to you by AJAX'
+ 'Your request was received at:'
+ 'Sunday 11 November 2018, 02:40:00 am'
var dateStr = text.match(/\w{3,4}day.*(?:am|pm)$/i);
var date = new Date(dateStr);
Edit:
Changed the quantifier to {3,6} so it matches Wednesday too.
Related
When used with .format('ll') I get a year, suffix, how can I fix the above to remove it?
E.g.: Jan 29, 2018 -> Jan 29
I try to use regular to replace, but it is quite complicated.
moment().format('ll').replace(new RegExp('[^\.]?' + moment().format('YYYY') + '.?'), '')
Jan 29, 2018 -> Jan 29,
reference: https://github.com/moment/moment/issues/3341
moment().format('ll')
.replace(moment().format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, '')
Thanks: Localizing day and month in moment.js
How about using Javascript split :
console.log(moment().format('ll').split(',')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
To remove the year and comma from the date string formatted with ll in moment.js, you can use the moment().format('MMM D') method, which will format the date in the format "MMM D" (e.g. "Jan 29"). Here's an example:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = moment(date, 'll').format('MMM D');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we first format the date string using ll, and then use the format method with the MMM D format to extract only the month and day. The resulting string will not include the year or comma.
Alternatively, you can use the replace method with a regular expression to remove the year and comma from the date string:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = date.replace(/, \d{4}/, '');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we use the replace method with a regular expression that matches a comma followed by a space and a four-digit year, and replace it with an empty string. This will remove the year and comma from the date string, leaving only the month and day.
I want to extract time from this string "Last Updated on Jul 9 2019, 3:15 pm +08"
<div id="demo"></div>
<script>
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var result = str.match(???);
if(result) {
document.getElementById("demo").innerHTML = result;
}
</script>
or is it possible to extract the date and time but in array form like ['Jul 9 2019','3:15pm']
I'm new to using regular expression and have no idea how to formulate the pattern. Thanks in advance!
You can use a positive lookbehind to find 'on' in the string, grab everything up to the pm/am, and split on the comma and space, assuming the format is consistent:
const str = "Last Updated on Jul 9 2019, 3:15 pm +08"
console.log(str.match(/(?<=on ).*(p|a)m/)[0].split(', '))
Note, the positive lookbehind feature is not compatible with all browsers, so I would recommend using adiga's approach if compatibility is an issue.
You could use the regex /on ([^,]+),\s*(.*(?:am|pm))/ with one capturing for date and another for time
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var result = str.match(/on ([^,]+),\s*(.*(?:am|pm))/);
result.shift();
console.log(result)
Regex demo
This can be done without using regex (assuming that the format of the time remains same like in the example you gave). Like this:
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var onlyTime = []
onlyTime.push(str.split(' ').slice(3,6).join(' ').slice(0, -1));
onlyTime.push(str.split(' ').slice(6,8).join(''));
console.log(onlyTime)
if you what use regular expression you can use '\d{1,2}:\d{2} (am|pm)' for find the time into the string of date. With \d{1,2} you have the digit between 1 and 60, with (am|pm) you find string 'am' OR string 'pm'.
I have the following string
XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018
Want to extract the data in below format:
Flight No : XX1366,XX4515,XX3416,XX1744
Flight Date : Monday 5 November 2018, Monday 5 November 2018, Monday 17 December 2018, Tuesday 18 December 2018
My Code : A, B, C, D (which is after the Flight No)
Could you help me to extract this data using regular expression?
This may be a bit laggy but should work, you can adapt it easily :
(XX[0-9]+)([A-Z])([a-zA-Z]+ [0-9]+ [a-zA-Z]+ [0-9]+)
Pleas note that you can always test your regex online at sites like https://regexr.com/
Surely not the most elegant solution, however the following works too:
XX(\d*)(\w)(\w*\s\d+\s\w*\s\d*)
As a sidenote in case you're wondering - people on the website are far more likely to answer your question if you have put in some effort beforehand. Basically it's a forum for coding help, rather than on-demand code-writers. :)
On option could be to use 2 capturing groups to match either XX followed by 4 digits or match any character and use a positive lookahead to assert that what followed is XX followed by 4 digits or the end of the string $
Then while looping the matches collect the values in an array and use join to show them comma separated.
(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))
Regex demo
const regex = /(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))/g;
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let m;
let flights = [];
let flightDates = [];
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m[1]) {
flights.push(m[1]);
}
if (m[2]) {
flightDates.push(m[2]);
}
}
console.log("Flight No: " + flights.join(','));
console.log("Flight Date: " + flightDates.join(', '));
Or you might use a combination of map and split to create a multidemensional array where the first value is for example XX1366 and the second Monday 5 November 2018 and you could extract those values. First split on the positive lookahead (?=XX\d{4}) and then split on matching \*\*[A-Z]\*\*
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/)
);
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/));
console.log("Flight No: " + res.map(x => x[0]).join(', '));
console.log("Flight Date: " + res.map(x => x[1]).join(', '));
I think this regex can help you :
Flight No : (XX[0-9]+)
Flight Date : [MTWFS][a-z]+ [0-9]{1,2} [a-zA-Z]+ [0-9]{4}
Code : (?<=\*)([A-Z])
You can use /y flag to match at last Index.
I have a string that contains a datetime in the following format
2016-07-30 00:00:01.0310000
I need to convert this to a datetime object in JavaScript retaining the sub-seconds.
If I use
var d = new Date('2016-07-30 00:00:01.0310000');
Everything after 01 is dropped, how can I efficiently achieve this?
You'll have to parse the string yourself (which is quite simple, the only tricky bit is trailing zeros on the milliseconds value) and build the date using the Date(years, months, days, hours, minutes, seconds, milliseconds) constructor. Or use a library and a format string.
Here's an example:
var str = "2016-07-30 00:00:01.0310000";
var parts = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)\s*$/.exec(str);
var dt = !parts ? null : new Date(
+parts[1], // Years
+parts[2] - 1, // Months (note we start with 0)
+parts[3], // Days
+parts[4], // Hours
+parts[5], // Minutes
+parts[6], // Seconds
+parts[7].replace(/0+$/, '') // Milliseconds, dropping trailing 0's
);
if (dt.toISOString) {
console.log(dt.toISOString());
} else {
console.log("date", dt.toString());
console.log("milliseconds", dt.getMilliseconds());
}
In the regex, \d means "a digit" and {x} means "repeated x times".
The !parts ? null : new Date(...) bit is so that if the string doesn't match the format, we get null rather than an error.
The milliseconds are saved (31), but what comes after that is not saved, because javascript does not support it.
You could use library like Moment JS, You can read more http://momentjs.com/docs/
var day = moment("2016-07-30 00:00:01.0310000");
console.log(day._d); // Sat Jul 30 2016 00:00:01 GMT+0100 (WAT)
I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );