Skip to content
Fix Code Error

Where can I find documentation on formatting a date in JavaScript?

March 13, 2021 by Code Error
Posted By: Anonymous

I noticed that JavaScript’s new Date() function is very smart in accepting dates in several formats.

Xmas95 = new Date("25 Dec, 1995 23:15:00")
Xmas95 = new Date("2009 06 12,12:52:39")
Xmas95 = new Date("20 09 2006,12:52:39")

I could not find documentation anywhere showing all the valid string formats while calling new Date() function.

This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn’t have a built-in API to format a date object into a string.

Editor’s note: The following approach is the asker’s attempt that worked on a particular browser but does not work in general; see the answers on this page to see some actual solutions.

Today, I played with the toString() method on the date object and surprisingly it serves the purpose of formatting date to strings.

var d1 = new Date();
d1.toString('yyyy-MM-dd');       //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome
d1.toString('dddd, MMMM ,yyyy')  //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome

Also here I couldn’t find any documentation on all the ways we can format the date object into a string.

Where is the documentation which lists the format specifiers supported by the Date() object?

Solution

I love 10 ways to format time and date using JavaScript and Working with Dates.

Basically, you have three methods and you have to combine the strings for yourself:

getDate() // Returns the date
getMonth() // Returns the month
getFullYear() // Returns the year

Example:

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
Answered By: Anonymous

Related Articles

  • Current time formatting with Javascript
  • What is a smart pointer and when should I use one?
  • How do I include certain conditions in SQL Count
  • Using CTE in Oracle SQL (ORA-00923: FROM keyword not…
  • Examples of GoF Design Patterns in Java's core libraries
  • Convert Java Date to UTC String
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • What are the valid Style Format Strings for a…
  • Ember.js - where should interface state be stored?
  • Smart way to truncate long strings
  • Clang vs GCC - which produces faster binaries?
  • SQL query return data from multiple tables
  • Design DFA accepting binary strings divisible by a…
  • How are zlib, gzip and zip related? What do they…
  • Best way to represent a Grid or Table in AngularJS…
  • How to implement a FSM - Finite State Machine in Java
  • What's the difference between Instant and LocalDateTime?
  • Interrupt an earlier timeout event in Simpy
  • Filter by Dates in SQL
  • How can I change color of date on the datepicker vuetify?
  • Why does Java 'break' statement not working?
  • Edge does not show div with Aurelia bindings which I…
  • apache not accepting incoming connections from…
  • What are the real-world strengths and weaknesses of…
  • Use of String.Format in JavaScript?
  • Aurelia UX showcase app fails to load
  • I want to align the text in my list element that…
  • Java string to date conversion
  • R dataframe format dates when some are prior to 1/1/1900
  • #define macro for debug printing in C?
  • Set value of object using function
  • Can't install via pip because of egg_info error
  • How to print a date in a regular format?
  • Rust calling fmt function directly
  • Java Enum Methods - return opposite direction enum
  • Get Datetime in 8601 format from SQL Server
  • Is there an opposite to display:none?
  • Aurelia app is not launched using au run cli command
  • How can I determine whether a 2D Point is within a Polygon?
  • Gson and deserializing an array of objects with arrays in it
  • How can building a heap be O(n) time complexity?
  • How to use java.net.URLConnection to fire and handle…
  • Best way to find the months between two dates
  • java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
  • What's the best way of scraping data from a website?
  • Best practices for API versioning?
  • How does PHP 'foreach' actually work?
  • SQL find sum of entries by date including previous date
  • How to turn off the Eclipse code formatter for…
  • Why does extracting a date from a dataframe work…
  • Best way to work with dates in Android SQLite
  • What is the standard Python docstring format?
  • How do i arrange images inside a div?
  • Is there a way to get two specific data together in…
  • The definitive guide to form-based website authentication
  • "Thinking in AngularJS" if I have a jQuery background?
  • Updating getter value Vuex store when state changes
  • How do I vectorize a Pandas function that counts…
  • Backbone.js: TypeError: Object # has no method 'parse'
  • Deprecation warning in Moment.js - Not in a…
  • Remove first n "words" from string variable in Bash
  • Ordering issue with date values when creating pivot tables
  • How to plot a very simple bar chart (Python,…
  • How can I find the product GUID of an installed MSI setup?
  • String.Format for Hex
  • Firebase Security Rules Block Writing to Firebase
  • How do you create a Swift Date object?
  • How to count input whenever the user input something…
  • data.table vs dplyr: can one do something well the…
  • why does this function not return the excpected tsrange[]
  • Where's the DateTime 'Z' format specifier?
  • ffmpeg usage to encode a video to H264 codec format
  • Can Smart Contract access Data of other Blockchains?
  • How to reformat a Vue.js component in vscode?
  • Accessibility and all these JavaScript frameworks
  • ASP.NET Core return JSON with status code
  • What does "Fatal error: Unexpectedly found nil while…
  • React useState not updating the states on submit form
  • What's the difference between eval, exec, and compile?
  • String formatting: % vs. .format vs. string literal
  • get an array of dates from today for datepicker with…
  • quick way to extract "valid" substring in c
  • Resampling Within a Pandas MultiIndex Loses Values
  • Using local private key with Web3.js
  • Can not connect to local PostgreSQL
  • Why is it that "No HTTP resource was found that…
  • How to add fade animation for this tab
  • How to serialize class to JSON, where property is of…
  • How to handle dates in Backbone?
  • How to format a phone number in a textfield
  • vuetify datepicker clear dates and re render component
  • XMLHttpRequest cannot load ✘✘✘ No…
  • How to add leading zeros?
  • Start redis-server with config file
  • What does "dereferencing" a pointer mean?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • How can i use `parse = T` and functions like round…
  • Converting seconds in date form Numpy Python
  • Conversion failed when converting date and/or time…
  • How to dispatch a Redux action with a timeout?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

map function for objects (instead of arrays)

Next Post:

How to emulate a do-while loop in Python?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error