vishnu
vishnu

Reputation: 425

Get the time from a date string

How do I get the time from the date string using JavaScript.

My datestring is in the following way: 2013-04-08T10:28:43Z

How to split the time in hours and minutes format. I want to show the activity stream in the following way:

xxx has updated 2hrs ago
yyy has updated 3min ago

Upvotes: 15

Views: 38095

Answers (5)

Bogdan Haidu
Bogdan Haidu

Reputation: 125

var curr_date = new Date();
var test_date = new Date("2016-01-08 10:55:43");

hours_diff=Math.abs(test_date.getHours()-curr_date.getHours());
minutes_diff=Math.abs(test_date.getHours()*60+test_date.getMinutes()-curr_date.getHours()*60-curr_date.getMinutes());
console.log("xxx has updated "+hours_diff+" hours ago");
console.log("xxx has updated "+minutes_diff+" minutes ago"); //not so beautiful

///STILL IF THE date is a string and !!NOT CREATED with DATE 
/// "Get the time from a date string" might have this solution

var date = "2016-01-08 10:55:43";
var hours = date.slice(-8);

console.log("hours and minutes string is "+hours);

fiddle test

Upvotes: -1

atondelier
atondelier

Reputation: 2434

Extract a date from your dateString

First extract the numbers with

var sp = dateString.match(/\d+/g)

Then you can build a Date object or skip this step

var dateObject = new Date(+sp[0], +sp[1]-1, +sp[2], +sp[3], +sp[4], +sp[5])

And call getHours and getMinutes on this Date object.

If you skip this then directly get +sp[3] for hours and +sp[4] for minutes.


Compute the difference

Since you seem to have to compare with now, you will get time difference this way:

var timeDifference = new Date(new Date - dateObject);

And then call getHours and getMinutes on timeDifference.

Upvotes: 1

mvladk
mvladk

Reputation: 628

Simple Javascript is more than enough: Date.parse will convert your string to timestamp:

var date_string = '2013-04-08T10:28:43Z';

var your_date_object = new Date();
your_date_object.setTime(Date.parse( date_string ));

var min = your_date_object.getUTCMinutes();
var hour = your_date_object.getUTCHours();

Upvotes: 2

Stasel
Stasel

Reputation: 1298

Just create new Date object:

var myDate = new Date("2013-04-08T10:28:43Z");

var minutes = myDate.getMinutes();
var hours = myDate.getHours();

Upvotes: 22

hbhakhra
hbhakhra

Reputation: 4236

This is whats known as an ISO string. There are utilities to parse ISO strings as regular JavaScript dates out there such as Dojo.

var date = dojo.date.stamp.fromISOString("2013-04-08T10:28:43Z");

http://dojotoolkit.org/reference-guide/1.8/dojo/date/stamp.html

Upvotes: 0

Related Questions