I have a page with blog posts on so I can’t adjust the output (no access to server-side code) but I want the date in Nov 4, 2022 format.
The HTML looks like this:
<span class="post-time">
<p>04/11/2022</p>
</span>
I know my date format is MMM D, YYYY but I cannot seem to get the code to output anything.
I have tried the following codes and can’t seem to figure out how to get the new date to output:
$(document).ready(function() {
// Variation 1:
var post_date = $(".post-time1 p").text().format('MMM D, YYYY');
$(".new-date p").text(post_date);
// Variation 2:
$(".new-date").val($(".post-time2 p").formatDate('MMM D, YYYY', new Date()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<span class="post-time1">
<p>04/11/2022</p>
</span>
<span class="post-time2">
<p>04/11/2022</p>
</span>
2
Answers
Here is a possible solution for your query.
Hopefully it can help you.
Result:
To achieve the desired date formatting, you’ll need to parse the existing date, format it in the desired way, and then update the target element. jQuery doesn’t have built-in methods for date formatting, but you can use plain JavaScript
Date
object methods or a library like Moment.js or Day.js.Here’s how you can do it using JavaScript without any additional libraries:
HTML:
jQuery Code:
Explanation:
.text()
to get the date string and.trim()
to remove any whitespace.DD/MM/YYYY
format, so split it using/
, then useDate(year, monthIndex, day)
to construct aDate
object (adjusting the month index as it’s zero-based).toLocaleDateString()
with appropriate options to format the date..text()
to update the content of.new-date p
.Output:
The
.new-date p
element will now containNov 4, 2022
.