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

Grid Column with Checkboxes in Kendo UI for Vue

Seeking help in adding a checkbox column to a Kendo UI Vue grid. The column should display the values of a boolean field from the grid's data source. While I am aware of how to add a checkbox column for selection as demonstrated here: https://www.tele ...

Rule: attribute should indicate a specific function

I am currently trying to implement the functionality from https://github.com/rpocklin/angular-scroll-animate in my project, but I keep encountering an error in my console: Error: Directive: angular-scroll-animate 'when-visible' attribute must ...

Encountering an issue when trying to generate a button in Angular

I am currently using JavaScript to dynamically create a button in Angular. While I have been successful in creating the button, I am encountering an error when attempting to change the classname. The error message I am receiving is: Property 'clas ...

Ensure the Firebase real-time database in Javascript purges the active session upon tab or browser closure

I need to implement a feature in my Firebase real-time database project using JavaScript where the current session is logged out automatically after closing the tab or browser. When I log in with my email and password, if I copy the URL and paste it into ...

How to Capture Clicks on Any DOM Element in React

Currently working on a web project using React and Node. My goal is to monitor all clicks across the entire document and verify if the previous click occurred within a 2-minute timeframe. ...

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Convenient method for extracting the final element within a jQuery section

I need to determine whether the div with the class "divclass" contains an anchor tag. If it does, I have to run a specific block of JavaScript code; otherwise, no action is required. <div class="divclass"> <span> some text</span> ...

Access a file from an npm module using an executable command

I have a npm module called @jcubic/lips, which includes an executable file. I need to open a file located within the module's directory. This module is installed globally. The specific file I want to access is ../examples/helpers.lips, relative to th ...

Is there a way in Python to translate JavascriptSerializer into a datetime object?

My JSON file contains date and time in the format generated by JavascriptSerializer, shown below: {"StartDate": "/Date(1519171200000)/", "EndDate": "/Date(1519257600000)/",} How can I convert it to datetime formats like these? "2012-04-23T18:25:43.511Z" ...

Perform an Ajax request to a C# Controller Function

In my javascript file named "data handling.js" within a folder labeled "JS", you'll find the following piece of code: document.getElementById('submit-new-project').addEventListener("click", function () { var ProjectName = document.getEl ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Angular js encountered an unexpected error: [$injector:modulerr] ngRoute

https://i.sstatic.net/PATMA.png In my Angular code, I encountered the error "angular is not defined". This code was written to test the routing concept in AngularJS. var app=angular.module('myApp',['ngRoute']) .config(function ($routeP ...

What is the best way to retrieve the responseText using the jQuery.getJSON method within JavaScript?

I am currently facing an issue where I am attempting to retrieve information from a JSON file located in my directory by utilizing the jQuery.getJSON method. Unfortunately, when I try to access the object shown in the image, I am unable to extract the resp ...

Navigating the storing and organizing of user data through Firebase's simplistic login feature for Facebook

As I work on my AngularJS and Firebase-powered website project, I aim to leverage Facebook login for seamless user connectivity. While Firebase's simple login feature promises an easier authentication process, I face the challenge of effectively acces ...

Transform the page into a Matrix-inspired design

I decided to transform the appearance of my web pages into a stylish The Matrix theme on Google Chrome, specifically for improved readability in night mode. To achieve this goal, I embarked on the journey of developing a custom Google Chrome extension. The ...

When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach: seeMore(){ this.setState({ seeMore: !this.state.seeMo ...

JavaScript Ajax request lags significantly in Internet Explorer, while it executes instantly in Firefox

So I have this jQuery .ajax() call set up to retrieve a List<string> of IP addresses from a specific subnet. I'm using a [WebMethod] on an .aspx page to handle the request and ASP.NET's JSON serializer to format the response for my Javascri ...

Utilize esbuild to monitor for any modifications, recompile the code, and automatically restart the express server

In my endeavor to develop a basic SSR-powered project using express + react, I find the need to monitor frontend and backend scripts concurrently in the development process. The primary objective is to utilize express routes in directing to react page com ...

An issue arose when attempting to load the page using jQuery

Currently, I am implementing the slidedeck jquery plugin on my webpage to display slides. While everything is functioning properly, I am facing an issue with the CSS loading process. After these slides, I have an import statement for another page that retr ...

Using bufferCount in Rxjs: Retrieving the latest values

Is there a method to access the most recent values emitted while using bufferCount(x), even if the buffer size does not reach x? For example, in the code snippet below, only [0, 1] is printed. I would like the output to also include [2] under certain circ ...