Extract portions of the date into individual variables

My current project involves creating a front-end interface for data stored in a JSON database. The date information is saved in the following format:

12/31/16

I am trying to extract each of these values individually. Is there a method to assign variables like this?:

var month = 12
var day = 31
var year = 16

Answer №1

If you're looking to validate your date raw value and ensure your code can support different cultures, consider using moment js.

Check out Moment.js here

Here's an example of how it can be used:

function updateDate(dateValue) {
  var selectedDate = moment(dateValue, 'MM/DD/YYYY');
  $('#day').innerHTML = selectedDate.date();
  $('#month').innerHTML = selectedDate.month() + 1; // months start at 0
  $('#year').innerHTML = selectedDate.year();
}
document.addEventListener('DOMContentLoaded', function () {
  var input = $('input');
  input.value = '12/31/2021';
  updateDate(input.value);
});
var $ = document.querySelector.bind(document);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js">
</script>
<input onchange="updateDate(this.value)" type="text" />
Year: <span id="year"></span>
Month: <span id="month"></span>
Day: <span id="day"></span>

Moment.js is a versatile time and date JavaScript framework that enables parsing and formatting dates and times based on specific patterns and locales. It's highly recommended in the development community!

Answer №2

To handle a date as a string, you can break it down by using the / separator, resulting in an array. Then, access each element of the array using its index to extract the individual values.

var _date = "12/31/16",
  splitDate = _date.split("/"),
  month = splitDate[0],
  day = splitDate[1],
  year = splitDate[2];
console.log(month, day, year)

Answer №3

It seems that there was a overlook by all of us (except for Matt.C) regarding the need to convert YY into YYYY - storing a year as two digits is considered very bad practice.

If we assume that all dates are in this century:

var dateString = "12/31/16";
var [month, day, year] = dateString.split("/"); // utilizing a new method
year = "20" + year; // if necessary

The above code should be converted to numbers using parseInt

An older and more compatible approach:

var dateString = "12/31/16",
    parts = dateString.split("/"),
    month = +parts[0],
    day = +parts[1], 
    year = parseInt("20" + parts[2]); // remove "20" if not needed

Take notice how moment.js also faces issues with 2 digit years.

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.

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

I seem to be having trouble getting Vue to recognize my components. Could it be that I am not registering them

I am currently working on developing a simple blog application using Laravel with Vue.js. I have successfully created custom components, registered them in my app.js file, and referenced them in the views by their component names. However, upon loading the ...

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...

Utilizing the handleChange method to manage multiple input fields

It is important to me that the function handleChange only updates the input value that is being changed. Specifically, if I modify the 'firstName' input, I want only that state to be updated, and the same applies to the 'lastName' input ...

Grunt integration for version control

After sticking to simple Html and Css for the longest time, I'm finally diving into JavaScript for a new project where I want to automate versioning. I've been following the SemVer Guidelines and my projects are currently versioned as "version": ...

image source that changes dynamically with a placeholder image

Currently, I am facing a certain issue. Unfortunately, I cannot provide a plunkr example as the image is sourced from a protected site and there are no open URLs available that constantly serve changing images. Additionally, I am unable to use a local anim ...

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

Optimal method for organizing individuals into teams using Google Apps Script

There are approximately 200 individuals in this particular department. Our goal is to form groups of 4, with each group consisting of members from different teams based in the same city. Each group must have one driver and three non-drivers, all sharing si ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

ERROR: Module 'jquery' not found in path 'C:....' when using Gulp and Browserify

Encountering an error: Error: Module 'jquery' not found in path 'F:...\newstyle\assets\lib\helper\html\img\js' at C:\Users...\AppData\Roaming\npm\node_modules&bs ...

My search field in Safari (desktop) doesn't respond to jQuery's .focus() function

My website has a hidden search field that appears when the user clicks on the search icon. I want to automatically bring focus to the search input so users do not have to click twice. This feature works perfectly in Chrome, but not in Safari (desktop). I t ...

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

Transferring a zipped file from the backend of SailsJS to the frontend of React Redux via

My SailsJS Backend is responsible for generating a zip File when requested by my React App with Redux on the Frontend. I am utilizing Sagas for asynchronous calls and fetch to make the request. In the backend, I have attempted various methods such as: //z ...