Organizing dates with Javascript

Is there a way to convert a string from this format :

2014-06-12T23:00:00

To another format using JavaScript, like so :

12/06/2014 23:00

Answer №1

As pointed out by @Xotic750, the key is in parsing an ISO8601 timestamp:

updateDate = function(dt, dayFirst){
    var year = dt.getFullYear().toString();
    //months start from zero
    var month = (dt.getMonth()+1).toString();
    var date  = dt.getDate().toString();
    var result = null;
    if(dayFirst)
        result = (date[1]?date:"0"+date[0]) + "/" + (month[1]?month:"0"+month[0]);
    else
        result = (month[1]?month:"0"+month[0]) + "/" + (date[1]?date:"0"+date[0]);
    result += "/" + year + " " + dt.toTimeString().split(" ")[0];
    return result;
}
parseUTCTime = function(dtstr) {
    var dt = null;
    var dtArr = dtstr.split(/[\-T:]/);
    dt = new Date(Date.UTC(parseInt(dtArr[0]), dtArr[1]-1, parseInt(dtArr[2]), parseInt(dtArr[3]), parseInt(dtArr[4]), parseInt(dtArr[5])));

    return updateDate(dt);
};
parseTime = function(dtstr) {
    var dt = null;
    var dtArr = dtstr.split(/[\-T:]/);
    dt = new Date(parseInt(dtArr[0]), dtArr[1]-1, parseInt(dtArr[2]), parseInt(dtArr[3]), parseInt(dtArr[4]), parseInt(dtArr[5]));

    return updateDate(dt, true);
};

parseUTCTime("2014-06-12T23:00:00");//-->"06/13/2014 03:30:00"

parseTime("2014-06-12T23:00:00");//-->"12/06/2014 23:00:00"

Answer №2

To utilize the Date methods available in Javascript, you can follow this example:

function getFormattedDate() {
    var dateInput = new Date('2014-06-12T23:00:00');
    var year = dateInput.getFullYear();
    var month = dateInput.getMonth() + 1;
    
    var day = dateInput.getDate() + 1;
    day = day < 10 ? '0' + day : day;

    var hours = dateInput.getHours();
    hours = hours < 10 ? '0' + hours : hours;

    var minutes = dateInput.getMinutes();
    minutes = minutes < 10 ? '0' + minutes : minutes;

    return month + '/' + day + '/' + year + ' ' + hours + ':' + minutes;
}

Answer №3

If you're looking to simplify things in this situation, it might be best to steer clear of using the Date object and follow @Ismael's advice by utilizing straightforward string manipulation.

Javascript

var dateStamp = '2014-06-12T23:00:00',
    dateTime = dateStamp.split('T'),
    date = dateTime[0].split('-'),
    time = dateTime[1].split(':'),
    formatted = date.reverse().join('/') + ' ' + time.slice(0, -1).join(':');

console.log(formatted);

Output

12/06/2014 23:00

Test it out on jsFiddle

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

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Guide on sending JSON data to a server and receiving JSON/XML in response with JSP

I am new to developing web applications. I have successfully created a dynamic web project using Java EE on a Glassfish server. Now, I am trying to enable clients to send data to the server using JSON and receive data from the server in either JSON or XML ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

Looping through objects and updating state based on a filter condition

Within my React state, there exists an array of objects similar to the following: timers: { id:"-LL-YVYNC_BGirSn1Ydu" title: "Project Title" project: "Project Name", elapsed: 0, runningSince: 0, }, { id:"-LL-YVYNC_BGirSn1Ydu-2", ...

Retrieve all documents with a matching objectId field in MongoDB

I built an API that can fetch all data from a table, but within this table there is an object ID reference to a user. Table 1 - Story | Table 2 - User api.get('/all_stories', function(req, res) { Story.find({}, function(err, stories) { ...

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

designing various containers and adjusting their divisions

I have a pop-up window that contains the code snippet below, defining a template within a "container": <form method="post" class="signin" action="#"> <div id='container'> <div> <div id="divFeeTitle"&g ...

What are some ways to modify attributes in a jQuery datatable?

Upon loading the page, I initially set serverside to false. However, under certain conditions, I need to change serverside to true without altering any other attributes. For example: $(tableID).DataTable({ serverSide : false; }); Changing it to: $(t ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

Tips for configuring CakePHP to trigger the second submit button when the enter key is pressed

My form includes two submit buttons: "cancel" and "find." While both buttons work correctly when clicked, pressing the enter key always triggers the submission of "cancel." I don't want to change the button order in the form. To address this issue, I ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

What is the best way to target all elements sharing a common class?

Currently, I have a Boolean variable stored in a hidden input field. When the user is signed in, it's set to false; otherwise, it's set to true. I have download buttons that should link to a file for download. My goal is to hide these buttons an ...

Is it possible to conduct brain.js training sessions multiple times?

Is there a way to specifically train my neural network with new information without having to retrain the entire model, considering the potential performance costs associated with it? The neural network was created using brain.js. ...

Pulling information from a database query to store it within a JavaScript variable

Using Ajax/JQuery, I successfully send the variable ($name) from page1.php to page2.php without refreshing the page. When the submit button is clicked, it sends me the var $name effectively. Additionally, in my JavaScript library for charts (AmCharts), the ...

JQuery's addClass function is not functioning properly

Check out the code snippet below: function toggleAccessRequests() { var buttonValue = $("#showAccessRequests").val(); if (buttonValue == "Show") { $(".hideAccessRequest").removeClass("hideAccessRequest"); $("#showAccessRequests").v ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...