How to Change Date Format in JQuery?

By Hardik Savani October 20, 2023 Category : jQuery

sometime, we may need to change date format mm/dd/yyyy, mm-dd-yyyy, DD-MM-YYYY, yyyy-mm-dd etc in jquery then you can do it using moment jquery library. here i will give you very simple example that way you can understand how it works, actually it's very easy to use and fantastic.

moment.js is a jquery plugin that provide to change date formate from string date. they also provide to compare date, difference between two dates etc. there are several things work with dates, it's like carbon. So i think if you are using jquery then must be use moment js plugin for change date format.

I posted in past there are several post regarding dates as listed here : How to change date format using date filter in AngularJS ?, How to change bootstrap datepicker with speific date formate example, Laravel 5 change date format using carbon example and also there are several posts available related to dates. you can find it by search.

Moment js through we can simply convert string date to specific date format. So you can use following syntax for change date format.

Syntax:

$(document).ready(function() {


moment(your_string_date).format(here_date_format);


});

Now we will see following simple example, in this example i give you three dates and then convert it into "DD-MM-YYYY" this format, So you can see bellow list how i give you.

1. July 1, 1994 : 01-07-1994

2. 1994-07-01 : 01-07-1994

3. 1994-07-01 : 01-07-1994

I give basic string of date, you can pass your data string and check it so let's see bellow full example, how it works.

index.html

<!DOCTYPE html>

<html>

<head>

<title>How to change date format in jquery using moment JS?</title>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

</head>

<body>


<div class="container">

<h2>Examples:</h2>

<ul>

<li>July 1, 1994 : <span id="first_date"></span></li>

<li>1994-07-01 : <span id="second_date"></span></li>

<li>1994/07/01 : <span id="third_date"></span></li>

</ul>

</div>


</body>


<script type="text/javascript">

$(document).ready(function() {


var first_date = moment("July 1, 1994").format('DD-MM-YYYY');

$("#first_date").text(first_date);


var second_date = moment("1994-07-01").format('DD-MM-YYYY');

$("#second_date").text(second_date);


var third_date = moment("1994/07/01").format('DD/MM/YYYY');

$("#third_date").text(third_date);


});

</script>

</html>

Ok, now you can run above full example, you can also get more information about moment js from here : moment js.

I hope it can help you....

Tags :
Shares