Date/Time format relative to date range

833 views Asked by At

I need to select appropriate date/time format depending on the date range I am working with. The date range could be a few weeks, days, hours, seconds (even milliseconds).

I've looked into moment.js and format.js but I'm hoping there's something better out there. I want to achieve something like highcharts daterange. These charts select appropriate formats for the datetime axis according to the range.

Any help would be appreciated.

2

There are 2 answers

1
Jedi On BEST ANSWER

Try this below code, it is still rough:

var start = new Date(2014,12,22);
var end = new Date(2014,12,23);

var range = end.getTime() - start.getTime(); // milliseconds
var seconds = range/1000;
var minutes = seconds/60;
var hour = minutes/60;
var days = hour/24;
var months = days/30;
var year = months/12;

var maxValue = [9999, 12, 31, 24, 60, 60];
var dateRange = [year, months, days, hour, minutes, seconds];
var dateFormat = ['#yr', '#mt', '#d', '#h', '#min', '#sec'];

var specifiedIndex = 0; // default format
for (var index = 0; index < maxValue.length; index ++)
{
    if ((dateRange[index] < maxValue[index]) && (dateRange[index] >= 1))
    { 
        specifiedIndex = index;
        index = maxValue.length;
    }
}
alert("format date = " + dateFormat[specifiedIndex]);

Thank you,

0
caridy On

First, we need to check if the CLDR (http://cldr.unicode.org/) data exists for this use-case, then you can open an issue here https://github.com/tc39/ecma402, and we can start looking for solution in javascript to display date ranges in relative form.