1

I struggled with wording the title, but basically I want a function where I can provide two dates and it would output something like: "2w" if the result was 15 days or "1y" if it was 13 months or "1m" if it was 4 or 5 weeks. Preferably down to the hour... but 1 day minimum.

I found a similar SO question but it's for PHP and isn't complete anyway: How to calculate the difference between two days as a formatted string?

recnac
  • 3,744
  • 6
  • 24
  • 46
  • Can you show us your code so far? This is pretty straight forward stuff, you've even got a code sample there. – Halcyon Apr 19 '13 at 16:48
  • Like you said, it's pretty straightforward but very meticulous. Given that, I was hoping such a function already existed and I wouldn't have to reinvent the wheel... It's a minor cosmetic convenience that I can't afford to spend time on. If I can't find an existing one I'll just display the "last updated" date instead of "updated 4 months ago". –  Apr 19 '13 at 16:52
  • And @RobertRozas, that blog post is pretty awesome. I still feel like this circumstance is a bit different though and it's a time-consuming function that likely already exists. Maybe not. –  Apr 19 '13 at 16:54
  • This JSfiddle is very close. I may be able to modify it easily: http://jsfiddle.net/x9paT/2/ –  Apr 19 '13 at 17:03

1 Answers1

1

There are a number of javascript date libraries out there that will do all you want and more. Here is an example using XDate

<div id="result"><div/>

var now = new XDate();

var then = new XDate(2013, 04, 01, 0, 0, 0, 0);

document.getElementById("result").textContent = now.diffWeeks(then).toFixed(1) + " Weeks";

Available of jsfiddle

Here is with Moments.js

<div id="result"><div/>

var then = moment("Dec 25, 1995");

document.getElementById("result").textContent = moment(then, "YYYYMMDD").fromNow();

also vailable on jsfiddle

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • When I changed the "then" date year to 2012 it resulted in a negative number. Also, this excludes all the logic for rounding to the nearest unit (y,m,w,d,h) –  Apr 19 '13 at 17:02
  • As I said there are other libraries available, also including Moments.js(http://momentjs.com/) and Datejs(https://code.google.com/p/datejs/) are 2 more, I'm sure one of them does exactly what he wants, whatever exactly that is. – Xotic750 Apr 19 '13 at 17:04