0

What i want is the possibility to convert the string "5 minutes ago", or the string "10 hours ago" to a javascript date object in an easy manner.

Date.parse expects a date string and i believe that function does not meet my requirements.

In PHP i can do something like this:

Code

$string = "5 minutes ago";
$now = date('Y-m-d H:i:s');
$d = strtotime($now . " + " . str_replace("ago","",$string));
echo "Current time: " . $now;
echo "<br>";
echo "Altered time: " . date('Y-m-d H:i:s',$d);

Output

Current time: 2016-12-03 20:56:33
Altered time: 2016-12-03 21:01:33

and

How can i convert the string "5 minutes ago" or "10 hours ago" into a javascript date object?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Dan-Levi Tømta
  • 796
  • 3
  • 14
  • 29
  • Possible duplicate of [Javascript equivalent of php's strtotime()?](http://stackoverflow.com/questions/4048204/javascript-equivalent-of-phps-strtotime) – Dekel Dec 03 '16 at 20:00
  • Seems like an X/Y problem, you probably have something that outputs those strings and does the conversion, there's rarely any need to reverse engineer that ? – adeneo Dec 03 '16 at 20:02

1 Answers1

0

Use a regex to recognize that you have something in the form "X units ago", convert units to milliseconds, multiply by X (after converting X from a string to a number), and subtract that number of milliseconds from the current time before you convert the current time to a string.

then = new Date((new Date())-60000)

will make then be 60 seconds ago

If s is the string "5 minutes ago" then

var m = s.match(/(\d+) ((minutes)|(seconds)|(hours)) ago/)

should give you m as an array such that m[1] is a string that sequence of one or more digits, in this case "5" and m[2] will be one of the strings "minutes", "seconds", or "hours".

Paul Buis
  • 805
  • 7
  • 7