1

I have this date 2015/08/06 06:00 and i want to convert it to 6th August 2015 at 6am. I know how to do this in php but having trouble with jquery.

var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
    var d = new Date('2015/08/06 06:00');
    var d_formatted = d.getDate() + '/' +  monthNames[d.getMonth()] '/' + d.getFullYear();

How do i get the date suffix and the time?

2
  • 3
    Libraries such as moment.js can do this for you. Commented Aug 6, 2015 at 15:46
  • thanks @ThiefMaster got it working with moment.js Commented Aug 6, 2015 at 15:58

4 Answers 4

2

Try this code, i have Fiddled your needs http://jsfiddle.net/j6tb81qy/

function DateFormat(arg)
{
  var monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"];

  var Dates;
  if(arg.getDate()==1)
    Dates =arg.getDate() + 'st';
  if(arg.getDate()==2)
    Dates =arg.getDate() + 'nd';
  if(arg.getDate()== 3)
     Dates =arg.getDate() + ' rd';
  if(arg.getDate()> 3)
  Dates = arg.getDate() +'th'

  var hours ='';
  console.log(Dates)
  hours = arg.getHours();
  if(arg.getHours() >12)
  {
    hours = (arg.getHours() %12)+ ' PM'
  }
  else          
  {
    hours =arg.getHours()+ ' AM'
  }

  Dates = Dates + ' ' + monthNames[arg.getMonth()] +' ' + arg.getFullYear().toString() + ' at ' + hours.toString();
  return Dates; 
}

var d = new Date();
var val= DateFormat(d);
alert(val);

//6th August 2015 at 6am
Sign up to request clarification or add additional context in comments.

Comments

1

I prefer to use moment.js to do this

$(function () {
  $('.date').each(function (index, dateElem) {
    var $dateElem = $(dateElem);
    var formatted = moment($dateElem.text(), 'MM-DD-YYYY').format('MMMM D');
    $dateElem.text(formatted);
   })
 });​

1 Comment

I use moment.js a lot
0

Using pure javascript:

var d = new Date();
var n = d.toString();

The result of n will be:

Thu Aug 06 2015 12:52:33 GMT-0300 (BRT)


http://www.w3schools.com/jsref/jsref_tostring_date.asp

2 Comments

how do i remove the GMT-0300 (BRT)?
Use slice function. n.slice(0,-15)
0

With Date object, there are couple of methods to retrieve time:-

  • getHours() and getUTCHours()
  • getMinutes() and getUTCMinutes()
  • getSeconds() and getUTCSeconds()
  • getMilliseconds() and getUTCMilliseconds()

References: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date#Methods

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.