0

I want to create a Date object in TypeScript (AngularJS) from this string: 08:00:00.000+01:00 in order to use a filter in the end to show only the hour and the minute:

.filter('toDate', () => {
    return input => {
        let date = Date.parse(input);
        return date;
    }
})

In the HTML:

{{ object.unformatedTimeString | toDate | date: 'H:m' }}

Does anyone know a good way how to parse such a time string?

6
  • 1
    Why don't you just pull the hour and minute from the string? let [hr, min] = str.split(':');. Why the conversion? Commented Mar 27, 2018 at 18:56
  • Because there is also timezone information in the time string. Better convert it correctly. Commented Mar 27, 2018 at 18:57
  • Have you considered using moment.js? It is much more versatile than javascripts date object. Commented Mar 27, 2018 at 18:58
  • @Igor it's also massive and complex. Worth it if you have a lot of date manipulations, but not necessarily for small stuff. Commented Mar 27, 2018 at 19:00
  • moment.js would be an option if it integrates nicely into AngularJS (1.6.x). Commented Mar 27, 2018 at 19:04

2 Answers 2

2
Let [ts, tz] = str.split(/[\+\-]/);
let [hr, min] = ts.split(':').map(Number);
let offsetSign = str.includes('+') ? 1 : -1;
let [offsetHr, offsetMin] = tz.split(':');
let offset = offsetSign * ((offsetHr * 1000 * 60 * 60) + (offsetMin * 1000 * 60));

let date = new Date();
date.setHour(hr);
date.setMinute(min);
let result = new Date(date.getTime() + offset);

Tedious, but not complex or difficult.

Sign up to request clarification or add additional context in comments.

1 Comment

There's no need to convert [hr, min] to Number as multiplication will convert them as required and you should do date.setHour(hr, min, 0, 0) to set the time in one go. This may return a Date before the current date, the OP should test thoroughly to ensure the logic is correct, it may need to set UTC hour and minute. ;-)
1

One solution is to adjust the time for the timezone, making it a UTC time, then apply it to the current UTC date, e.g.

function parseToUTCTime(s) {
  var now = new Date();
  var b = s.match(/\d+|\D/g);
  var sign = b[7]=='+'? 1 : -1;
  now.setUTCHours(+b[0] + sign*b[8], +b[2] + sign*b[10], 0, 0);
  return now;
}

// Tests
['08:00:00.000+01:00',
 '06:30:00.000-08:00',
 '04:15:00.000+05:30'].forEach(ts =>
   console.log(ts + ' -> ' + parseToUTCTime(ts).toISOString())
 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.