0

How do get different form of date datetime and full date depending upon the scenarios.

  1. 1 In case date is newest less than 24 Hr old then I have to show like 22:31
  2. In case date is of same month for e.g february but older than 24 hr then I have to show like 15 Feb.
  3. In case date is older than a month then I have to show like 15 Feb 17.

Till now I have made two javascript function for the purpose .

function getLocalizeDateTime(dateString,format) {
if(dateString==null || dateString==undefined || dateString==""){
    return "";
}
var dateTime = dateString.trim().split(" ");
var dateOnly = dateTime[0];
var timeOnly = dateTime[1];
timeOnlyOfDate = timeOnly;
var temp = dateOnly + "T" + timeOnly+"Z";
var utc_date =new Date(temp);
currentDateStr = dateString;

//var offset = new Date().getTimezoneOffset();
//utc_date.setMinutes(utc_date.getMinutes() - offset);
  if(format!=undefined && format!=null)
  return date2str(utc_date,format);
  return date.toString();
 }

function date2str(x, y) {
var z = {
    YR: x.getFullYear(),
    M: x.getMonth() + 1,
    d: x.getDate(),
    h: x.getHours(),
    m: x.getMinutes(),
    s: x.getSeconds()
};

// Here return 22:32 if date is less than 24 hr old.
// return 24 feb as currentmonth is feb.
// return 24 feb 17 in case current date is march or greater.
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
    return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2)
});

return y.replace(/(y+)/g, function(v) {
    return x.getFullYear().toString().slice(-v.length)
 });

}

But these functions return whole date in format for e.g for date "2017-02-24 07:46:38" and format MM-dd-yyyy hh:mm" it is returning 02-24-2017 13:16. How do acheve above mentioned 3 business check.

glen maxwell
  • 193
  • 1
  • 3
  • 13
  • Take a look at [momentjs](https://momentjs.com) – Ulysse BN Feb 24 '17 at 02:29
  • There are lots of formatting libraries. [*fecha.js*](https://github.com/taylorhakes/fecha) is concise and does parsing and formatting. – RobG Feb 24 '17 at 02:55
  • Possible duplicate of [How do you get a timestamp in JavaScript?](http://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript) – glen maxwell Apr 12 '17 at 12:20

2 Answers2

0

If you can be sure of support for toLocaleString options, they can be used to format the date string. Otherwise, use a library, e.g.:

function formatTime(date) {
  var now = new Date();
  var timeOpt = {hour:'2-digit', hour12:false, minute:'2-digit'};
  var monthOpt = {day:'numeric', month:'short'};
  var fullOpt = {day:'numeric', month:'short', year:'2-digit'};
  if (now - date < 8.64e7) {
    return date.toLocaleString(undefined, timeOpt);
  }
  if (now.getFullYear() == date.getFullYear() &&
      now.getMonth() == date.getMonth()) {
    return date.toLocaleString(undefined, monthOpt);
  }
  return date.toLocaleString(undefined, fullOpt);
}

// Tests
var soon = new Date();
soon.setHours(soon.getHours() - 2, 23);
var sameMonth = new Date();
sameMonth.setHours(sameMonth.getHours() - 25);
var agesAgo = new Date(2016,5,6,14,27,50);

[soon, sameMonth, agesAgo].forEach(function(date){
  console.log(formatTime(date));
})

The sameMonth test will use the fullOpt on the first of the month or before 01:00 on the second as it will set the date to the previous month, but otherwise it will show the more than a day but same month result.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

This is my solution. Basically I just cut up the dates to perform conditional tests on them and then stitched them back together. The advantage is that it uses no libraries to do it.

I did grab the 'subtract one day' code from another answer [Link].

$(document).ready ( function() {
    var less_than_24 = getLocalizeDateTime(new Date('Fri Feb 24 2017 10:41:28'));
    var same_month = getLocalizeDateTime(new Date('Fri Feb 16 2017 13:41:28'));
    var older_than_month = getLocalizeDateTime(new Date('Fri Jan 24 2017 13:41:28'));

    console.log('less_than_24:  ' + less_than_24);
    console.log('same_month:  ' + same_month);
    console.log('older_than_month:  ' + older_than_month);
});

function getLocalizeDateTime(dateString,format) {

    var monthNames = ['Jan','Feb','Mar','Apr','May','Jun',
        'Jul','Aug','Sep','Oct','Nov','Dec'];

    if (dateString==null || dateString==undefined || dateString=="") {
        return "";
    }

    var now = new Date();

    var hours_24_ago = now;
    hours_24_ago.setDate(hours_24_ago.getDate() - 1);

    if (dateString >= hours_24_ago) {
        return dateString.getHours() + ':' + dateString.getMinutes();
    } else if (dateString.getFullYear() == now.getFullYear() 
            && dateString.getMonth() == now.getMonth()) {
        return (dateString.getDate() + ' ' + monthNames[dateString.getMonth()]);
    } else {
        return (dateString.getDate() + ' ' 
            + monthNames[dateString.getMonth()] + ' ' 
            + dateString.getFullYear());
    }
}
Community
  • 1
  • 1
CERich
  • 1
  • 1