I am trying to extract the date from the following object (that has been stringified.)
I am new to regular expressions, and not sure how to go about it.
I tried /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/gmi -> but it didnot work.
{"Date":"2016-05-16","Package Name":"com.myapp.mobile","Current Device Installs":"15912","Daily Device Installs":"41","Daily Device Uninstalls":"9","Daily Device Upgrades":"3","Current User Installs":"12406","Total User Installs":"23617","Daily User Installs":"27","Daily User Uninstalls":"8"}
Don't use a Regex here.
Do JSON.parse(str).Date, unless there is a really good reason not to (you haven't stated one in your question)
If you want to turn the string "2016-05-16" into 3 variables for Year, Month and day (without using a date library), I'd just use .split():
dateArray = "2016-05-16".split("-")
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
Your regex matches fine, just don't use the /gmi flags
"2016-05-16".match(/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/)
You can make it a bit simpler yet..
"2016-05-16".match(/(\d{4})-(\d{2})-(\d{2})/)
But, you really should be using a library for this, like moment.js, or at least Date which will work fine because this ISO-8601.
const date = new Date("2016-05-16");
date.getYear();
As suggested in comments, you can get the date by parsing the JSON (trimmed in the following for convenience):
var s = '{"Date":"2016-05-16","Package Name":"com.myapp.mobile"}';
var dateString = JSON.parse(s).Date;
document.write(dateString);
If you want a Date object, you can then parse the string. Note that using either the Date constructor or Date.parse for parsing strings is not recommended due to browser inconsistencies. Manually parsing an ISO date is fairly simple, you just need to decide whether to parse it as local or UTC.
Since ECMA-262 requires the date–only ISO format to be parsed as UTC, the following function will do that reliably (and return an invalid date for out of range values):
/* Parse an ISO 8601 format date string YYYY-MM-DD as UTC
** Note that where the host system has a negative time zone
** offset the local date will be one day earlier.
**
** #param {String} s - string to parse
** #returs {Date} date for parsed string. Returns an invalid
** Date if any value is out of range
*/
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[0], b[1]-1, b[2]));
return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}
var d = parseISODate('2016-05-16');
document.write('UTC date: ' + d.toISOString() + '<br>' +
'Local date: ' + d.toString());
Related
I'm working with Javascript within Google Sheets, and I'm having trouble converting or parsing a formatted timestamp, to ultimately extract the day as a numerical value.
My code:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
Logger.log(date.getDay());
The output:
[19-06-10 17:40:56:107 BST] NaN
My goal is to extract the day number, for example, "18" from that timestamp.
However, it doesn't seem to convert it. I suspect my timestamp isn't in the correct format for the date() function, so it's about creating a function to parse it.
Hopefully, you can help me with that! :) Thank you so much.
The date object has a method like this for getting the day of the month as a number (1-31).
date.getDate();
18 is date.
var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
console.log(date.getDate());
JavaScript's Date constructor supports ISO 8601 date strings. Without using any libraries, you can do something like this:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
+ 'T' + shopifyTimestamp.slice(11, 19)
+ shopifyTimestamp.slice(20);
var date = new Date(isoDate);
console.log(date.getDate()); // 18
Also note that you're looking for date.getDate(), rather than date.getDay(). The latter returns the numerical date of the week.
This question already has answers here:
javascript: how to parse a date string
(4 answers)
Closed 5 years ago.
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.
The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.
How to solve this problem?
Thanks in advance.
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:
/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}
console.log(parseDate('2017:03:09 14:49:21').toString());
It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:
var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
You can do simple string manipulation and create date if the format is always the same, as:
var str = "2017:03:09 14:49:21".split(" ");
//get date part and replace ':' with '-'
var dateStr = str[0].replace(/:/g, "-");
//concat the strings (date and time part)
var properDateStr = dateStr + " " + str[1];
//pass to Date
var date = new Date(properDateStr);
console.log(date);
I have a string in GMT "2017-01-17 00:00:00.000" and I want to get time and date differently (the string does not have to be in that format).
I tried:
var datetime = new Date(calEvent.start);
var date = datetime.toLocaleDateString(); //output: 1/16/2017
var time = datetime.toLocaleTimeString(); //output: 4:00:00 PM
but the output for date and time I want should be in GMT timezone. Anyone know how to do that without using substring for string?
Thanks
The string "2017-01-17 00:00:00.000" is not consistent with the subset of ISO 8601 specified in ECMA-262 and will not be parsed correctly in some browsers. As it is, it will be treated as local if parsed at all.
You can modify the string by adding a "T" between the date and time and a trailing "Z" for UTC, then let the Date constructor parse it, e.g.
var s = '2017-01-17 00:00:00.000';
var d = new Date(s.replace(' ', 'T') + 'Z');
console.log(d);
Which will work in most modern browsers, however it will fail in older browsers like IE. You can also write a small function to parse the strting as UTC:
function parseAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1] - 1, b[2], b[3], b[4], b[5], b[6]));
}
console.log(parseAsUTC('2017-01-17 00:00:00.000'));
You can also use one of the various libraries available, however if all you need it to parse one particular format, then that's not necessary.
NOTE:
It's generally not recommended to parse strings with the Date constructor (or Date.parse) as they are largely implementation dependent, however the ISO 8601 extended format is now fairly well supported and is specified in ECMA-262.
The time zone must be specified with upper case "Z". Firefox (at least) will generate an invalid date if "z" is used.
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I'm using an API to call a date from a post.
Dates are returned in ISO 8601 format :
2015-11-09T10:46:15.097Z
I want my dates to be formatted like this :
09/11/2015
Then, later, I want to insert them into my HTML, like this :
$(data).each(function(){
var html = '<randomhtml> '+this.created_at+' <randomhtml>
$('#stream').append(html);
});
Does anyone know how I can change my date to right format?
The easiest would be to just work with the string
$(data).each(function(){
var date = this.created_at.split('T') // split on the "T" -> ["2015-11-09", "10:..."]
.shift() // get the first part -> "2015-11-09"
.split('-') // split again on "-" -> ["2015", "11", "09"]
.reverse() // reverse the array -> ["09", "11", "2015"]
.join('/') // join with "/" -> "09/11/2015"
var html = '<randomhtml> ' + date + ' <randomhtml>';
$('#stream').append(html);
});
As it's a UTC date, just passing it do new Date() would add the difference of the timezone, and not always output the correct date.
If you need to validate the date, there are regexes for checking valid UTC dates.
this can be solve your problem
var date = new Date('2015-11-09T10:46:15.097Z');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
output will be "09/11/2015"
For date manipulation momentjs library is very useful.
If you want to make date format dependent on users country you can additionally use formatjs.
All browsers
The most reliable way to format a date with the source format you're using, is to apply the following steps :
Use your time string as input for new Date()
Use .getDate(), .getMonth() and .getFullYear() to get respectively the day, month and year
Paste the pieces together according to your target format
The format function below shows you the optimal way to combine those four steps :
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
var date = new Date(input);
return [
("0" + date.getDate()).slice(-2),
("0" + (date.getMonth()+1)).slice(-2),
date.getFullYear()
].join('/');
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(See also this Fiddle).
Note
While this approach does work in all browsers, you'll need an additional step before new Date(input) to parse your ISO 8601 format if you need to support browsers as old as IE8--. See the accepted answer at Javascript JSON Date parse in IE7/IE8 returns NaN for a function that does exactly that.
Modern browsers only
You can also use the built-in .toLocaleDateString method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
return new Date(input).toLocaleDateString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(See also this Fiddle).
(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build
The simplest and most reliable way to reformat a date string is to just reformat the string. So use split (or match) to get the values and return them in the order you want, ignoring the bits you don't need, e.g.:
function isoToDMY(s) {
var b = s.split(/\D/);
return b[2] + '/' + b[1] + '/' + b[0];
}
document.write(isoToDMY('2015-11-09T10:46:15.097Z'));
If you want the output date to also consider the host system time zone (e.g. 2015-11-09T20:46:15Z in a timezone that is UTC+0530 will be 2015-11-10T02:16:15Z)), then you should manually parse it to a Date object and then get year, month and day values.
A library can help with parsing, but a function to parse and validate the values is only a few lines.
I'm using the Javascript Date(string) constructor with a date format of "yyyy-mm-dd". The constructor works just fine in IE 9 and Firefox unless the app is running on our testing VM which is running IIS. If it's on the VM, in IE 9 it returns 'NaN', but still works normally in Firefox.
var dateAsString = "2011-11-09";
var dateCreated = new Date(dateAsString);
I was under the assumption that the server had nothing to do with client-side Javascript. Any suggestions?
And for those of us who want to know how to replace hyphens (aka dashes) with slashes:
new Date(dashToSlash(string));
That uses this function:
function dashToSlash(string){
var response = string.replace(/-/g,"/");
//The slash-g bit says: do this more than once
return response;
}
In my case it's much easier to convert hyphens to slashes selectively (only where it's needed for the Date() function) than to replace the date format everywhere in my code.
Note: you really need to define a separate 'response' variable and assign it the value of the replace operation result. If you don't, the string is returned unaltered in Chrome. That's not a huge problem, since Chrome doesn't have a problem with hyphenated date strings to begin with. But still...
Just use slashes instead of hyphens if you can.
EDIT: Expanded clarification...
The ISO 8601 standard format uses the hyphen as a date separator. My answer does not mean you do not need to follow standards. You can use slashes only for the Date constructor if necessary.
It's because of the date format. For some reason, IE and Safari get tripped up with yyyy-mm-dd. Use another date format and you should be all set.
It's talked about here:
http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari
I suggest attempting a more reliable form of date parsing. The example below uses setFullYear(). Does IE produce a different result with the code below?
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Source: http://jibbering.com/faq/#parseDate