javascript novice
javascript novice

Reputation: 777

Regular Expression Pattern match for Date

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"}

Upvotes: 0

Views: 902

Answers (3)

RobG
RobG

Reputation: 147363

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());

Upvotes: 0

rjmunro
rjmunro

Reputation: 28056

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];

Upvotes: 1

Evan Carroll
Evan Carroll

Reputation: 1

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();

Upvotes: 0

Related Questions