JavaScript - Ways to retrieve the date in the desired format

Looking to display the Date output in 2 different formats. Below is my current attempt:

<p id="demo"></p>

<script>
var d = new Date(day, month);
document.getElementById("demo").innerHTML = d.toString();
</script>

Unfortunately, the above code is not producing the desired output for me.

My goal with this code is to achieve the following output: 21 Jun

Additionally, I am interested in learning how to obtain the date in this format:

Jun 21, 2016 12:00 AM

Answer №1

const monthsArr = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const currentHour = dateObj.getHours();
let period = "AM";
if (currentHour > 12) {
    currentHour -= 12;
    period = "PM";
}
const formattedDate = monthsArr[dateObj.getMonth()] + " " + dateObj.getDate() + ", " + dateObj.getFullYear() + " " + currentHour + ":" + dateObj.getMinutes() + " " + period;

Answer №2

let currentTime = new Date();
let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
let hours = currentTime.getHours();
let period = "AM";
if (hours > 12) {
    hours -= 12;
    period = "PM";
}
let displayDate = months[currentTime.getMonth()] + " " + currentTime.getDate() + ", " + currentTime.getFullYear() + " " + hours + ":" + currentTime.getMinutes() + " " + period;
document.getElementById("demo").innerHTML = displayDate.toString();

Give this code a shot.

Answer №3

If you're looking to format dates in JavaScript, you'll need to handle it manually as the language itself doesn't provide built-in functions for this task. A simple code snippet for a basic date format can get you started:

<p id="demo"></p>

<script>
  var d = new Date(2016, 5, 21);
  document.getElementById("demo").innerHTML = getMonthName(d.getMonth()) + " " + d.getDate();

  function getMonthName(month) {
    var monthnames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    return monthnames[month];
  }
</script>

Feel free to customize this code for any other date format you require. Keep in mind that there are numerous libraries available to simplify date formatting tasks. Utilizing one of these libraries can save you time and effort instead of reinventing the wheel.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function inArray() in jQuery will return a value of -1 when an array consists of

When using jQuery inArray, if the array contains only one element, it will return -1. var a = Array(1); console.log($.inArray(1,a)); This result is -1. However, if the array has 2 or more elements, it functions correctly. var a = Array(1,2,3); console.l ...

Output data to file in a sequential order using JavaScript

I am struggling to comprehend this particular issue. In the context of executing the runOneCombination function across numerous files, my goal is to extract specific information, perform calculations, and then append the results to a file. However, the ch ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

What is the proper technique for inserting a variable into the header portion of a v-data-table from a JavaScript file?

I'm currently developing an application using Vue.js with datatables. I need to display the headers of a v-data-table component, and ideally, I would like to pass a variable that can be dynamic based on the language selected on the page. Below is the ...

The default selection for React Material Multiselect items is not being chosen

Currently, I am working on implementing the React Material autocomplete component that includes a multiple-values checkbox. However, it seems like there is an issue with the defaultValue prop and the checkboxes example. Even though I set defaultValue to a ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Counting each item with jQuery and assigning them numbers 02, 03, 04, etc., with the exception of the first item which will display as "Up Next

I'm still learning jQuery and here's the code I've put together after researching on stackoverflow and other platforms: var counter = 1; $('.next-page .nav-item').each(function () { if ($(this, ':gt(0)')) { $(this ...

Tips on modifying the interface based on the selected entry using jQuery

I am attempting to display a text when different options are selected from the dropdown list. Here is the code for the drop-down list: <div class="dropdown"> <select class="form-control" id="ltype" name="ltype"> <option value=""&g ...

The basic function is ineffective when used within an if-condition

I am currently dealing with a JSON file that has some nesting: { "name": "1370", "children": [ { "name": "Position X", "value": -1 }, {...} ] "matches": [ { "certainty": 100, "match": { "name": "1370 ...

The function `jQuery .html('<img>')` is not functional in Firefox and Opera browsers

This particular code snippet jq("#description" + tourId).html('<b>Opis: </b> '+ data); has been tested and functions correctly in Internet Explorer, Firefox, and Opera. However, when it comes to this specific piece of code jq("#i ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...

How can we utilize CSS floats to achieve maximum widths?

I currently have 5 divs that I need to structure in a specific way: Each div must have a minimum size of 100px The parent container should display as many divs as possible on the first row, with any remaining divs wrapping to new rows if necessary If the ...

Upon loading the page, trigger the controller method by utilizing the information from the query string

Can query string data be retrieved on page load with javascript? Here is how I am attempting to achieve this in my project: The view page displays tabular data. When a button is pressed, it retrieves the row's id and invokes a javascript function. ...

Angular Material has support for displaying nested optgroups within select components

Upon reviewing a question on Stack Overflow, I learned that nested optgroups are not supported in the HTML5 spec. While it is possible to manually style them, I am curious if Angular Material offers a solution. Angular Material internally swaps many eleme ...

Stopping autoplay in Swiper as soon as you hover over it

My swiper is set to autoplay, but I want it to stop immediately when hovered over instead of waiting for the transition to finish. Is there a way to interrupt the transition and stop it at the exact point where the cursor hovers? Here is my Swiper config ...

Multi-line input in ExtJs

Is there a way to create a multiline input with vertical scrollbars in EXTJS? I tried the following code: noteField = new Ext.form.TextField({ emptyText: 'note...', multiline: true, applyTo: &apos ...

Changing the content of a PHP div with an Ajax callback inside another Ajax callback?

In the index.php file, there is a script that triggers an ajax call when a header element is clicked. This call sends a $selection variable to ajax.php, which then replaces #div1 with the received HTML data. <script> $(document).ready(function(){ ...

What method would you recommend for modifying HTML text that has already been loaded using JSP?

Is there a way to update text on an HTML document without reloading the entire page? I'm looking to create a simple "cart" functionality with 5 links on a page. When a link is clicked, I want it to increment the "items in cart" counter displayed on th ...

Finding the Closest Element with jQuery's .closest() Method

I'm facing an issue while trying to select an element that is positioned above another element. Specifically, I want to target the nearest occurrence of the .discount-dropdown class that appears above the .discount-type class. Can anyone help me figur ...