0

I Want Date and Time In 12 Hour Format.

function view_users(id)
{
  var td = data.CreatedOn;
  var dateTime = new Date(td*1000);
  var Created = dateTime.toString();           
  $('#CreatedOn').text(Created);
}

Right Now i am getting Following OutPut.

Created:Fri Jan 11 2019 09:21:13 GMT+0530 (India Standard Time)
Sagar
  • 47
  • 1
  • 6
Hemil
  • 227
  • 3
  • 16

3 Answers3

0

there are many way to convert time. I want to try to answer with my way :

var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var date = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var second = now.getSeconds();
var times ='';

if(hours>12){
  times = '0'+hours%12 +':'+minutes+':'+second+' PM'
}
else{
  times = '0'+hours%12 +':'+minutes+':'+second+' AM'
}

console.log(year+'-'+month+'-'+date+' '+times);

You can use another way, and pardon me if this is not best answer

Wicak
  • 399
  • 4
  • 12
0

You can Try this

 function format_time(date_obj) {
      // formats a javascript Date object into a 12h AM/PM time string
      var hour = date_obj.getHours();
      var minute = date_obj.getMinutes();
      var amPM = (hour > 11) ? "pm" : "am";
      if(hour > 12) {
        hour -= 12;
      } else if(hour == 0) {
        hour = "12";
      }
      if(minute < 10) {
        minute = "0" + minute;
      }
      return hour + ":" + minute + amPM;
    }
0

If you don't need much date formatting, and don't need to support anything below IE11, the following minimal example should work.

const date = new Date();

console.log(date.toLocaleString());

You may need to input the options as well if it does not work to your liking like so:

date.toLocaleString('en-US', { hour12: true })

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

launster
  • 1
  • 2