Juggling various date formats in JavaScript

I've come across similar questions numerous times, but I haven't found a concrete solution yet. Here are the steps I'm currently following:

  1. Within my HTML code, I have an <input type="date"> element that, when clicked, displays a calendar with dates in dd/mm/yyyy format.
  2. To store the date in my database, I convert the HTML5 date to a timestamp using Date.parse(html5Date). On the server side, I manipulate the date and send it back to my Angular application.
  3. Then, I convert the timestamp back to a Date object using new Date(timestamp). To display the date in a user-friendly format within a table, I join the day, month, and year like so:
    [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/')
    .
  4. During an edit operation (PUT request), I retrieve the date from the HTML, convert it to a timestamp, send it to the server, and handle the returned date back into an HTML date value.
  5. In addition to these tasks, I perform various other date-related functionalities such as comparisons, adding hours to dates, displaying the time of day, etc., directly within the HTML markup.
  6. All of these seemingly simple operations collectively make up over 120 lines of code, which, in my opinion, is not only excessive but also prone to errors. I've explored using an Angular Datepicker component, but found it confusing. Moreover, inconsistencies exist where the HTML date is sometimes treated as an Object and other times as a String, leading to errors with Date.parse().
  7. Are there any developer-friendly techniques available for efficiently carrying out the following process: copy the HTML5 date (from the Datepicker) --> convert it to a timestamp (for Angular and server-side handling) --> format the timestamp back to a string or object (for updating the HTML)? Thank you!

Please note: Angular may generate several error messages in the console related to incorrect date formats (stemming from the HTML date type), while still allowing the code to execute.

Answer №1

It seems like you may be performing too many conversions. In my opinion, dates should only be represented as Date objects in the programming language. There are only a couple of conversions that are necessary:

Date <=> Integer milliseconds since the epoch to send to server
Date <=> String human-readable format for user display

Anything beyond this could lead to issues. Comparisons can be done by converting to an integer using date.getTime(), comparing, and then converting back to a Date. The same goes for additions. It's important to note that Date.parse behavior is implementation specific in terms of what it accepts, although all implementations will accept ISO 8601 formatted date strings while anything else is ambiguous. This means you may have to manually handle string conversions, similar to the function below:

var toDate = str => {
   var splitter = str.indexOf("/") === -1 ? "-" : "/";
   var [mon, day, year] = str.split(splitter);
   return new Date(year, mon - 1, day);
};

var toDateString = date => {
  return "" + date.getFullYear() + (date.getMonth() + 1) +...
};

Please remember that there is no validation included here, so it will be up to the user to handle that.

THOUGHTS ON MOMENT.JS

Moment.js is fantastic. However, it is also quite large and contains a wide range of features. Since you're already utilizing Angular, consider carefully whether adding another sizable library is worth increasing your payload size.

Answer №2

Moment.js is a fantastic tool for working with dates and times, providing powerful formatting and manipulation capabilities. The convenience of being able to accomplish complex tasks with just a single line of code in Moment.js cannot be overstated. Personally, I find that without utilizing a library like Moment.js, managing date formatting and handling becomes much more cumbersome.

http://momentjs.com/

UPDATE: For anyone curious, I integrate Moment.js into my Angular application and have found it to be incredibly beneficial!

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

Obtaining a value from within an Angular 'then' block

I have a unique issue that I haven't been able to find a solution for on StackOverflow: Within an Angular 6 service, I am trying to call a function from another service using TypeScript. Here is the code snippet: Service1: myArray: Array<IMyInte ...

What could be causing the "Undefned Jquery-ajax" error to pop up

I am struggling with the following code. My goal is to populate values into a dropdown <select> box, but I keep receiving an error of undefined. I have tried switching between Object.keys and Object.values, however, I am still facing the same issue. ...

Mastering the art of using regular expressions (regex) in AngularJS' $httpBackend Expect

When passing a URL as a parameter in a $resource GET request, Angular automatically encodes the parameter. This can make matching the request in the $httpBackend.expectGET method difficult. I've tried using regular expressions to match the expected r ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

jQuery validation on select box change event

A project I'm working on involves designing a show/hide feature for a div select box using select2 and validating it using the jQuery validation plugin. Everything seems to be working fine, except for one issue I've encountered. When I select an ...

Conceal the input field prior to making a selection from the dropdown menu

I have implemented a drop-down menu for selecting dependencies, similar to how it functions in JSFiddle. $('#user_time_zone').on('change', function() { dateCalender = $(this).val(); if (dateCalender == 'Single Date') { ...

Why React.js and webpack are restricting the use of var, let, const?

I'm facing a puzzling issue that I just can't seem to solve. Let me show you a snippet from my Graph.js file: class Graph extends React.Component { @observable newTodoTitle = ""; s = 40 The error in webpack is showing up like this: E ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

The date format in MongoDb is structured uniquely to provide

When performing bulk inserts into MongoDB using NodeJs (native driver), I encountered an issue with storing a date field as Date rather than String. The dates are in the format dd/mm/yyyy, but currently, I am converting them to mm/dd/yyyy format by iterati ...

Mysterious pop-up notification in jQuery

When I run the code below, instead of receiving "Hello" in the alert box, I am getting an undefined message. Could you please take a look and correct any errors? jQuery tutorial <input type="text" id="name" value="Hello"> </body> ...

Sending an array of JSON objects using jQuery is a simple and straightforward process. By

I'm currently facing a challenge while working on my web page - I am struggling to send an Array of JSON objects to my PHP backend script. Below is the JavaScript code I have been using (with jQuery): var toSend = new Array(); ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: https://i.sstatic.net/g1wDj.png This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon docu ...

Guide to implementing an $http post service with defer and promise in AngularJS

var myAppModule = angular.module('myApp', []); myAppModule.controller('mainController', function($scope, userService) { $scope.addUser = function() { var email = $scope.user.email; var password = $scope.user.password ...

Converting HTML5 FormData object to raw payload using frontend javascript: A Step-by-Step Guide

Can anyone help me with extracting the entire POST request payload stream in my browser side script? I am facing difficulty when the body is a FormData object, especially containing a file blob. Is there a convenient way to achieve this? The main purpos ...

What steps can be taken to extend the duration that the HTML necessary validation message is displayed?

Is it possible to extend the duration in which the HTML required validation message is displayed? Currently, it seems to appear for too short a time. https://i.sstatic.net/DdqH6.jpg ...

A custom JavaScript function designed to facilitate the downloading of a file that includes the user's input directly to the user

Is there a way to use javascript to generate a file based on user input and provide it as a download without storing it on the server? For instance, imagine a scenario where a user is using an application and they want to download their work by clicking ...

Need to update the dropdown selections once the flag has been modified

I am facing an issue in AngularJS where I am using the select function with a group by feature. Depending on a flag value from the database, I need to either hide or show certain options within the select dropdown. However, since the flag takes some time t ...

When Axios is disconnected, the sequence of events following a user's action is no longer dependent on when it is called after a button

I am working on a script that performs the following actions: Upon clicking a button, an encoded text is sent to an API for decoding. The decoded text is then used as a query for a Google search link that opens in a new tab. JAVASCRIPT // Summary: // ...