shaun
shaun

Reputation: 1273

Parsing strings for Math operations in Javascript

I have two values. one a [STRING] and one an [INT] TimeZone is a string of one of these values:

'EST-5:00' || 'CST-6:00' || 'MST-7:00' || 'PST-8:00'

DST will be an INT of 0 || 1.

Trying to figure out how best to get offset. offset = MATH.abs(TimeZone# + DST) ie.

let offset = MATH.abs(-5 + 1) // = 4 ('EST-5:00') + (DST = 1)

or

let offset = MATH.abs(-6 + 0) // = 6 ('CST-6:00') + (DST = 0)

or

let offset = MATH.abs(-8 + 1) // = 7 ('PST-8:00') + (DST = 1)

What is the best way to parse the string to get the number value and add the value of DST?


My end goal is actually to get a DateTime I have such as:

let DateTime = '2017-05-11 10:34:43'

along with the TimeZone String above (retrieved from metadata related to the event) and transform it to UTC using the DST Int (retrieved from metadata related to the event) ...

So I am trying to find out how much I need to add (hours) to the DateTime to set it to UTC given the data I have to work with.

so

let utcTime = moment(DateTime).add(offset, 'h');

Upvotes: 1

Views: 69

Answers (2)

RobG
RobG

Reputation: 147413

You only want the number part, so you can use a regular expression to get the hour and minute values:

var tz = 'EST-5:00';
var hm = tz.match(/[+-]?\d\d?/g);

will get the time parts. hm[0] is the hour part with sign and `hm[1] is the minute part. If you want the letter part as well, that can be accommodated too:

var hm = tz.match(/[a-z]+|[+-]?\d\d?/ig);

Some timezones go down to 15 minutes and daylight offsets can be 30 minutes, so it's more compatible to express the offset in minutes than hours (though it should be in ±hh:mm format for humans). You should also keep the minutes part and the sign:

var tz = 'EST-5:00';

function offsetToMins(s) {
  var hm = s.match(/[+-]?\d\d?/g) || []; // Avoid null
  var h = hm[0] * 60;
  var m = +hm[1];

  // A bit of validation
  if (isNaN(h) || isNaN(m)) {
    return 'Invalid input: ' + '"' + s + '"';
  }

  return h + (h<0? m*-1 : m);
}

console.log(offsetToMins(tz))          // -300
console.log(offsetToMins('IST+05:30')) // 330
console.log(offsetToMins('foo'))       // Invalid input: "foo"

Now the daylight saving offset can be added in minutes and the value can be presented in a suitable human readable format, e.g. -06:00, -6:00, -0600, whatever.

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19772

You could do a regular expression with a match group on the digit:

var value = '(\'PST-8:00\')'.match(/\w{3}-(\d{1})\:/).pop() + DST // => 8 + DST

It looks for a series of 3 word characters, followed by a hyphen, and then matches on a single digit, before ending at a colon character.

This was just a quick on off the top of my head, so I'm sure there are ways to tighten up the regex, but the principle is still the same (see the String.prototype.match docs on MDN).

Upvotes: 1

Related Questions