1

My Script:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<input type="text" id="date_time" value="<?php echo date('Y-m-d H:i:s'); ?>">
<script type="text/javascript">
    $(document).ready(function(){
        var date_time = $('#date_time').val();
        alert(date_time); // return 2015-08-18 11:58:21
    });
</script>
</body>
</html>

It's alert in the format 2015-08-18 11:58:21, but i want to convert my date and time format, using javascript, to 18 August 2015, 11:58 AM.

3 Answers 3

2

As you are using jQuery, so you can use Moment.js plugin to convert date and time as you needed. It's relay ease to use.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
</head>
<body>
<input type="text" id="date_time" value="<?php echo date('Y-m-d H:i:s'); ?>">
<script type="text/javascript">
    $(document).ready(function(){
        var date_time = $('#date_time').val();
        date_time = moment(date_time, "DD MMMM YYYY, hh:mm A");
        alert(date_time); // return 18 August 2015, 11:58 AM
    });
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

"It's really ease to use". How about showing him some example code of how to use the "moment.js" plugin?
1

Try this :

<script>
var given_date = '2015-11-18 11:58:21';
var date_arr = given_date.split(" "); 
var ymd = date_arr[0];
ymd = ymd.split('-');

var y = ymd[0];
var m = ymd[1];
var d = ymd[2];

var his = date_arr[1];
his = his.split(':');

var h = his[0];
var i = his[1];
var s = his[2];

var ampm = (h >= 12) ? "PM" : "AM";
var months = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December'];

$('#date').html(d + ' ' + months[m-1] + ' ' + y + '   ' + h + ':' + i + ' ' +  ampm);
</script>

Comments

1

Change your date format to

<?php
 echo date("F j, Y, g:i a"); ?>

It's return // August 18, 2015, 3:37 pm

Read date format

2 Comments

First Thanks for giving answer but i want this conversion in javascript not in php can you help me ??
If date is coming form database you can easily converted into your data format using php . Why you use JavaScript fot it??

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.