1

I have an string that contains month/date and I need to insert the year. The string looks like:

Last Mark:: 2/27 6:57 PM

I want to convert the string to something like:

Last Mark:: 2010/02/27 18:57

In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.

What is the best method for this?

3 Answers 3

2

Following from Adam's suggestion:

function convertDate(yourDate) {
   var today = new Date();
   var newDate = new Date(today.getFullYear() + '/' + yourDate);

   // If newDate is in the future, subtract 1 from year
   if (newDate > today) 
       newDate.setFullYear(newDate.getFullYear() - 1);

   // Get the month and day value from newDate
   var month = newDate.getMonth() + 1;
   var day = newDate.getDate();

   // Add the 0 padding to months and days smaller than 10
   month = month < 10 ? '0' + month : month;     
   day = day < 10 ? '0' + day : day;

   // Return a string in YYYY/MM/DD HH:MM format
   return newDate.getFullYear() + '/' +
          month + '/' +
          day + ' ' +
          newDate.getHours() + ':' +
          newDate.getMinutes();
}

convertDate('2/27 6:57 PM');  // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM');  // Returns: "2009/03/27 18:57"
Sign up to request clarification or add additional context in comments.

2 Comments

Now it's less simple, but more powerfull and less error-prone :D GW
@Adam: hehe... at least I've sprinkled some comments in there :)
1

the code for adding THIS year is simple

var d = Date();
var withYear = d.getFullYear() + yourDate;

however, the logic behind considerating if it should be this year or last year could be harder to do

I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()

Comments

0

This returns the current year:

var d = new Date();
var year = d.getFullYear();

To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.

To get the day and month from the Date object:

d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate();  // this is 1-indexed (1-31)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.