User
User

Reputation: 194

Problems with Date Object on javascript

I need to know how long the message was written.

window.date = function (o){
    var r = new Date('1970-01-31 23:59:59').getTime();
    var a = new Date().getTime()-new Date(o).getTime();
    /*o=the date of the message: 2017-04-18 17:00:00*/
    if(new Date().getFullYear()>new Date(o).getFullYear()){
        n = 'more than a year ago';
    }else if(new Date().getMonth()>new Date(o).getMonth()){
       if(j=>r){
           n = 'less than a month ago';
        }else{
           n = 'more than a month ago';
        }
     }else{
        n = 'error'
      }

The problems are these: 1)if you write a message on 31/03 you see after a day(01/04): 'more than a month ago'(it's only one day from the date) 2)if you write a message on 17/04 and today(18/04) you try to read you don't read 'less than a month ago', but you read 'error'. Really i try, but in this page i don't read the solution:https://www.w3schools.com/jsref/jsref_obj_date.asp Can you show me a hypothetical solution?

Upvotes: 0

Views: 290

Answers (1)

Tyler Roper
Tyler Roper

Reputation: 21672

Just subtract the amount of time you'd like to check from today's date, and compare it to the date you're checking. If the date you're checking is earlier than the result, then it's over "that amount of time" ago.

A function for this might look like the following:

function checkDate(o) {
    var today = new Date();
    var dateToCheck = new Date(o);
    var monthAgo = new Date(); monthAgo.setMonth(today.getMonth() - 1);
    var yearAgo = new Date(); yearAgo.setFullYear(today.getFullYear() - 1);

    if (dateToCheck < yearAgo) {
        return "Over a year ago.";
    } else if (dateToCheck < monthAgo) {
        return "Over a month ago.";
    } else {
        return "Less than a month ago."
    }
}

Here's an example of it in use:

function checkDate(o) {
    var today = new Date();
    var monthAgo = new Date();
    monthAgo.setMonth(today.getMonth() - 1);
    var yearAgo = new Date();
    yearAgo.setFullYear(today.getFullYear() - 1);
    var dateToCheck = new Date(o);

    if (dateToCheck < yearAgo) {
        return "Over a year ago.";
    } else if (dateToCheck < monthAgo) {
        return "Over a month ago.";
    } else {
        return "Less than a month ago."
    }
}

alert(checkDate(new Date(prompt("Enter a date (mm/dd/yyyy)"))));

Upvotes: 1

Related Questions