Monica
Monica

Reputation: 1534

How do I get the time in milliseconds from 2 different string?

I have the following code which I get from parameters in the URL.

This is what I have in the URL &dateStart=15.01.2015&timeStart=08%3A00&

After getting the parameters I have the following: 15.01.2015:08:00

Using Javascript how can I parse this string to get the date in milliseconds?

Date.parse(15.01.2015:08:00)

But obviously this doesn't work.

Date.parse(15-01-2015)

This works and I can change this but then how do I add or get the milliseconds from the time??

Upvotes: 0

Views: 89

Answers (5)

Kami
Kami

Reputation: 19457

Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.

var dateStart = '15.01.2015'
var timeStart = '08:00';

var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);

var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);

var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());

Upvotes: 1

Alternatex
Alternatex

Reputation: 1552

This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.

function millisecondsFromMyDateTime(dateTime) {
    var dayMonth = dateTime.split('.');
    var yearHourMinute = dayMonth[2].split(':');

    var year = yearHourMinute[0];
    var month = parseInt(dayMonth[1]) - 1;
    var day = dayMonth[0];
    var hour = yearHourMinute[1];
    var minute = yearHourMinute[2];

    var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);

    return dateTimeObj.getTime();
}

It will work with the format that your DateTime is in aka day.month.year:hours:minutes.

Upvotes: 2

gyzerok
gyzerok

Reputation: 1428

You can try to use moment.js library like this:

moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32175

You can achieve it using Javascript Date Object and JavaScript getTime() Method:

var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));

Here is a DEMO Fiddle.

Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.

Upvotes: 1

Related Questions