0

I have to format date as below using Jquery, I tried with Date.js and some more external JS but unable to do so:

Input value: 
Date val: 20150306 
Time :185900


Expected format:
time:  6.59 PM 
Date :Mar 06, 2015
8
  • 1
    Your question is not clear enough, what are you trying to achieve? Commented Mar 6, 2015 at 10:02
  • 1
    How would 20150306 ever become Oct 06, 2015? Commented Mar 6, 2015 at 10:06
  • @Magrangs basically tring to format a date and time using jquery Commented Mar 6, 2015 at 10:06
  • 2
    Right, but how can 03 = October? Commented Mar 6, 2015 at 10:08
  • 2
    Try Moment.js, wonderful library Commented Mar 6, 2015 at 10:42

1 Answer 1

1

Here is my version (untested)

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

date = "20150306",
time = "185900",

//http://www.w3schools.com/jsref/jsref_slice_string.asp
date_year = date.slice(0, 4),
date_month = date.slice(4, 6),
date_day = date.slice(6, 8),
time_hours = time.slice(0, 2),
time_mins = time.slice(2, 4),
time_secs = time.slice(4, 6),

//http://www.w3schools.com/jsref/jsref_obj_date.asp
dateObj = new Date(date_year, date_month, date_day, time_hours, time_mins, time_secs, 0),
dateString = [monthNames[dateObj.getMonth() - 1], " ", dateObj.getDate(), ", ", dateObj.getFullYear()].join(""),

//Bit of Math
timeHours = dateObj.getHours() % 12 || 12,
timeSuffix = time_hours >= 12 ? 'PM' : 'AM',
timeString = [timeHours, ':', time_mins, ' ', timeSuffix].join("");

console.log("Date: " +  dateString);
console.log("Time: " +  timeString);
Sign up to request clarification or add additional context in comments.

1 Comment

Urgh... That hurts my eyes.

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.