-2

I currently am setting a cookie in my code that last for 10 minutes. On the page I want to tell the person how many minutes are left before the cookie expires. So what I do is set Another code to keep the time when the cookie was set.

But I don't know how to subtract the 2 time (the cookie time - current time).

For example, if I set the cookie at 12:55. How would I get the different between the time, lets say: 1:03 to get "2 minutes left"?

Really have no clue how to do this, but I hope you do.

Shawn31313
  • 5,978
  • 4
  • 38
  • 80
  • 3
    [What have you tried?](http://whathaveyoutried.com/) – sczizzo Jun 16 '12 at 05:33
  • 2
    possible duplicate of [How do I get the difference between two Dates in JavaScript?](http://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript) – Brad Jun 16 '12 at 05:34
  • @sczizzo I didn't try anything. I dont know what to try. – Shawn31313 Jun 16 '12 at 05:37

1 Answers1

3

You can just subtract dates in JavaScript.

var millisecondsBetween = (new Date(2012, 1, 1)) - (new Date(2011, 1, 1));

will yield the number of milliseconds between them because the - operator coerces its arguments to numbers which ends up calling Date.prototype.valueOf which just returns the number of milliseconds since the start of the epoch.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • You can put time inside the Date also: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date – Aram Kocharyan Jun 16 '12 at 05:45
  • 1
    @Shawn31313 this is exactly what you need. – Esailija Jun 16 '12 at 05:51
  • 1
    and I need to display it in minutes. I dont get how this is anything what i need. – Shawn31313 Jun 16 '12 at 05:54
  • 2
    @Shawn31313 - Did you learn Math in your school? 1 second has 1000 milliseconds, so 1 minute 60000 milliseconds. If you get `120000` from subtracting two dates (times), then that means `2 minutes`. – Derek 朕會功夫 Jun 16 '12 at 06:01
  • 1
    Yes I understand that. I have a cookie with a time like this: "8:42" and then I need to subtract the current time to get the difference. So no. This isn't what im looking for. – Shawn31313 Jun 16 '12 at 06:05
  • 1
    @Shawn31313 `(new Date() - new Date( 2012,5,16, 8, 42, 0 , 0 ,0 )) / 60000` gives me `25` when I ran that code 9:07. – Esailija Jun 16 '12 at 06:07
  • 1
    You asked how to subtract time values, not how pull time values out of a string. – sczizzo Jun 16 '12 at 06:09
  • From `12:01`, to pull out hour: `/^(\d+):/`, minute: `/(\d+)$/`. `txt.match(/^(\d+):/)[1]` is `12`. – Derek 朕會功夫 Jun 16 '12 at 06:11
  • Thanks @Esailija for the example. Never really took time to learn much about the Date object so I forgot that you can get the time with that also. Thank you. – Shawn31313 Jun 16 '12 at 06:40