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

Enhance video playback by eliminating accidental scrolling through the space bar

When using a video player, I always prefer to pause it by pressing the spacebar. However, this function is not working as expected. The issue at hand is that instead of pausing the video, pressing the space bar causes the page to scroll down unexpectedly ...

Select the send all text option when making a request

Using ajax, I can dynamically fill a drop-down select menu. My next step is to include all the text from the selected options in my request. <select name=".." > <option value="0"> ... </option> <option value="1"> xxx </option ...

Incorporating and modifying a component's aesthetics using styled-components: A comprehensive guide

My OverviewItem component has 2 props and is a styled-component. I want to change just one style on this component, which can be done by using the technique of styling any component. Does creating a wrapper component remain the only option for sharing st ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...

What is the process for validating observations with an observer confirmation?

Can you explain what the of() function creates in this scenario and how it operates? public onRemoving(tag): Observable<any> { const confirm = window.confirm('Do you really want to remove this tag?'); return Observable.of(tag).fil ...

The useEffect function is failing to execute when deploying on Vercel with Vite and React Router

After successfully deploying a React site using Vite on Vercel, with React Router for routing and a separate backend service, everything seemed to be working fine on my local machine. However, when testing the deployment on Vercel, I encountered an issue w ...

What is the process for obtaining Style.css, additional CSS, and JavaScript files from a live single page website?

I am currently facing a challenge with a live single page website where I need to make some fixes. Unfortunately, I am unable to access the Style.css file, along with other css and javascript files. Although I managed to save the html file by using Ctrl+s, ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Facing an issue with Heroku deployment where a React/Express app is encountering a 'Failed to load resource' error in the console while requesting the chunk.js files

Upon deploying my React application on Heroku, I encountered errors in the console. Refused to apply style from 'https://radiant-tor-66940.herokuapp.com/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Struggling with implementing a conditional template component within an AngularJS directive

As a Java/Python developer, I found myself working on an AngularJS project recently. While most concepts were easy to grasp, some of the syntax and functionality still elude me. The code I have handles login/logout functionality. If the user is logged in ...

Tips for showcasing personalized validation alerts with jQuery in the HTML5 format?

One of the Javascript functions I designed is for validating file extensions before uploading: function validateFileExtension(field, extensions){ file_extension = field.val().split('.').pop().toLowerCase(); if ($.inArray(file_extension,exten ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

Limit file selection to images using MUI File Input

I am currently using MUI File Input in React for a file input element. The code I have works well, but I would like to restrict this file input to only accept images. How can I achieve this? Here is what I have done so far: const [locationImg, setLoc ...

Posting and deleting data in AngularJS using HTTP requests

Incorporating both angularjs and c# webapi in this situation. My approach involves calling the webapi from angularjs and passing a json array. Here is the Angularjs code snippet: factory.delete = function (json) { var url = 'myUrl'; ...

The Selenium driver's execute_script method yields no result

One of the tasks I have is to determine if a specific element is within view. If it is, I want the script to return True; otherwise, False: driver.execute_script('window.pageYOffset + document.querySelector(arguments[0]).getBoundingClientRect().bottom ...

Generating new elements on the fly using jQuery and passing a string parameter through the onclick event

While dynamically creating HTML, I encountered a syntax error. If I modify href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')", I receive an error stating &a ...