user892134
user892134

Reputation: 3214

Javascript, convert date to different format

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?

Upvotes: 1

Views: 111

Answers (4)

Neo Vijay
Neo Vijay

Reputation: 873

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

Upvotes: 2

onelaview
onelaview

Reputation: 1133

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

Upvotes: 0

rma
rma

Reputation: 187

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

Upvotes: 0

blackmind
blackmind

Reputation: 1296

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);
   })
 });​

Upvotes: 1

Related Questions