A node.js package for Steven Levithan's excellent dateFormat() function.

Overview

dateformat

A node.js package for Steven Levithan's excellent dateFormat() function.

Build Status

Modifications

  • Removed the Date.prototype.format method. Sorry folks, but extending native prototypes is for suckers.
  • Added a module.exports = dateFormat; statement at the bottom
  • Added the placeholder N to get the ISO 8601 numeric representation of the day of the week

Installation

$ npm install dateformat
$ dateformat --help

Usage

As taken from Steven's post, modified to match the Modifications listed above:

var dateFormat = require("dateformat");
var now = new Date();

// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!

// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007

// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
dateFormat(now);
// Sat Jun 09 2007 17:46:21

// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22

// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST

// And finally, you can convert local time to UTC time. Simply pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
// 10:46:21 PM UTC

// ...Or add the prefix "UTC:" or "GMT:" to your mask.
dateFormat(now, "UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC

// You can also get the ISO 8601 week of the year:
dateFormat(now, "W");
// 42

// and also get the ISO 8601 numeric representation of the day of the week:
dateFormat(now, "N");
// 6

Mask options

Mask Description
d Day of the month as digits; no leading zero for single-digit days.
dd Day of the month as digits; leading zero for single-digit days.
ddd Day of the week as a three-letter abbreviation.
DDD "Ysd", "Tdy" or "Tmw" if date lies within these three days. Else fall back to ddd.
dddd Day of the week as its full name.
DDDD "Yesterday", "Today" or "Tomorrow" if date lies within these three days. Else fall back to dddd.
m Month as digits; no leading zero for single-digit months.
mm Month as digits; leading zero for single-digit months.
mmm Month as a three-letter abbreviation.
mmmm Month as its full name.
yy Year as last two digits; leading zero for years less than 10.
yyyy Year represented by four digits.
h Hours; no leading zero for single-digit hours (12-hour clock).
hh Hours; leading zero for single-digit hours (12-hour clock).
H Hours; no leading zero for single-digit hours (24-hour clock).
HH Hours; leading zero for single-digit hours (24-hour clock).
M Minutes; no leading zero for single-digit minutes.
MM Minutes; leading zero for single-digit minutes.
N ISO 8601 numeric representation of the day of the week.
o GMT/UTC timezone offset, e.g. -0500 or +0230.
p GMT/UTC timezone offset, e.g. -05:00 or +02:30.
s Seconds; no leading zero for single-digit seconds.
ss Seconds; leading zero for single-digit seconds.
S The date's ordinal suffix (st, nd, rd, or th). Works well with d.
l Milliseconds; gives 3 digits.
L Milliseconds; gives 2 digits.
t Lowercase, single-character time marker string: a or p.
tt Lowercase, two-character time marker string: am or pm.
T Uppercase, single-character time marker string: A or P.
TT Uppercase, two-character time marker string: AM or PM.
W ISO 8601 week number of the year, e.g. 4, 42
WW ISO 8601 week number of the year, leading zero for single-digit, e.g. 04, 42
Z US timezone abbreviation, e.g. EST or MDT. For non-US timezones, the GMT/UTC offset is returned, e.g. GMT-0500
'...', "..." Literal character sequence. Surrounding quotes are removed.
UTC: Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The "UTC:" prefix is removed.

Named Formats

Name Mask Example
default ddd mmm dd yyyy HH:MM:ss Sat Jun 09 2007 17:46:21
shortDate m/d/yy 6/9/07
paddedShortDate mm/dd/yyyy 06/09/2007
mediumDate mmm d, yyyy Jun 9, 2007
longDate mmmm d, yyyy June 9, 2007
fullDate dddd, mmmm d, yyyy Saturday, June 9, 2007
shortTime h:MM TT 5:46 PM
mediumTime h:MM:ss TT 5:46:21 PM
longTime h:MM:ss TT Z 5:46:21 PM EST
isoDate yyyy-mm-dd 2007-06-09
isoTime HH:MM:ss 17:46:21
isoDateTime yyyy-mm-dd'T'HH:MM:sso 2007-06-09T17:46:21+0700
isoUtcDateTime UTC:yyyy-mm-dd'T'HH:MM:ss'Z' 2007-06-09T22:46:21Z

Localization

Day names, month names and the AM/PM indicators can be localized by passing an object with the necessary strings. For example:

var dateFormat = require("dateformat");
dateFormat.i18n = {
  dayNames: [
    "Sun",
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat",
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ],
  monthNames: [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ],
  timeNames: ["a", "p", "am", "pm", "A", "P", "AM", "PM"],
};

Notice that only one language is supported at a time and all strings must be present in the new value.

Breaking change in 2.1.0

  • 2.1.0 was published with a breaking change, for those using localized strings.
  • 2.2.0 has been published without the change, to keep packages refering to ^2.0.0 to continue working. This is now branch v2_2.
  • 3.0.* contains the localized AM/PM change.

License

(c) 2007-2009 Steven Levithan stevenlevithan.com, MIT license.

Comments
  • Uncaught TypeError: Invalid date

    Uncaught TypeError: Invalid date

    I am using this package with webpack on browser side.

    I am using it like this.

    var formatDate = require('dateformat'); 
    

    but I am getting this error. "Uncaught TypeError: Invalid date"

    notice that, I am getting this error even when not use.

    I think this problem about this line

    opened by alioygur 13
  • consider moving cli to different lib

    consider moving cli to different lib

    I love using this, but I just realized that it's using meow, and I'm guessing that a good percentage of users like myself probably aren't using the CLI, but the dependency tree for it is absurdly massive. Especially considering this would have zero deps without it.

    meow has 48 dependencies in total, this is its flattened dependency tree (along with the number of times each module appears in the tree):

    {
      'trim-newlines': 1,
      'redent': 1,
      'strip-indent': 1,
      'get-stdin': 1,
      'indent-string': 1,
      'repeating': 1,
      'is-finite': 1,
      'number-is-nan': 1,
      'read-pkg-up': 1,
      'read-pkg': 1,
      'path-type': 1,
      'pinkie-promise': 4,
      'pinkie': 4,
      'pify': 2,
      'graceful-fs': 2,
      'normalize-package-data': 1,
      'load-json-file': 1,
      'strip-bom': 1,
      'is-utf8': 1,
      'parse-json': 1,
      'error-ex': 1,
      'find-up': 1,
      'path-exists': 1,
      'object-assign': 1,
      'validate-npm-package-license': 1,
      'spdx-expression-parse': 1,
      'spdx-license-ids': 2,
      'spdx-exceptions': 1,
      'spdx-correct': 1,
      'semver': 1,
      'is-builtin-module': 1,
      'builtin-modules': 1,
      'hosted-git-info': 1,
      'minimist': 1,
      'loud-rejection': 1,
      'camelcase-keys': 1,
      'map-obj': 1,
      'camelcase': 1
    }
    
    opened by jonschlinkert 11
  • Multiple simultaneous i18n translations support

    Multiple simultaneous i18n translations support

    Hello Felix,

    I'd like to use this library at the start-up I'm part of, but we need to support multiple languages for our users (starting with English and Spanish, with immediate plans to expand to Portuguese, French, and Italian shortly after launch), and swapping the i18n object on every request isn't a nice solution, so I've patched the i18n object to be a hash table of ISO 639-1 codes (though you could always use 639-2 if need be; no restriction enforced).

    It's done through a nullable fourth parameter, so this won't break the usage of the dateformat function, but the restructuring of the i18n object would break others' code if they are replacing the object as it currently stands.

    David

    opened by dfellis 9
  • Fix broken timezone abbreviations and GMT fallback

    Fix broken timezone abbreviations and GMT fallback

    This PR aims to fix what both #104 and #165 attempted to do, this time with tests to ensure it works as expected and doesn't break in the future.

    The gist is this:

    The Z formatting option attempts to generate a nice timezone abbreviation by parsing the rendered date string, recognizing something like "Eastern Daylight Time" and changing that to EDT. For all unrecognized timezones (pretty much everything but common North American timezones) it would parse and display the GMT+xxxx offset from the date string instead.

    This, however caused a couple of issues with Australian timezones. Because Australia has defined an "Australian Eastern Daylight Time" (for instance) it would erroneously match the same regex as the American "Eastern Daylight Time" and it would render as EST instead of AEST. Adding explicit support for the "Australian " prefix fixes this issue.

    The GMT+xxxx fallback worked prior to #165 but it was broken, probably accidentally while rebasing #104 in an attempt to get it into a merge-able state. This PR fixes the issue introduced by #165 and adds some tests to ensure it doesn't get inadvertently broken in the future.

    /cc @chase-manning

    opened by mikegreiling 8
  • Update time zone abbreviations

    Update time zone abbreviations

    Uses list of time zone abbreviations. https://en.wikipedia.org/wiki/List_of_time_zone_abbreviations

    I expanded the regular expression to use all time zone abbreviations.

    As an example AEST time zones are being clipped to just EST. This change fixes that problem. It also fixes unreported problems with other time zones. According to Wikipedia the longest time zone is five characters.

    opened by matthewbadeau 7
  • Fix incorrect work with double-quoted substrings.

    Fix incorrect work with double-quoted substrings.

    Their content was not ignored. Original function works correctly.

    // correct
    dateFormat('2017-06-16', "'yyyy'") // yyyy
    
    // wrong
    dateFormat('2017-06-16', '"yyyy"') // "2017"
    
    opened by anikolaev 6
  • Adding `p` as timezone offset, e.g. `+02:00`

    Adding `p` as timezone offset, e.g. `+02:00`

    Because the feed validator for ATOM complains about timezone offset being given as +0200 and not as +02:00, I added a slight modification of the o and called it p (like in PHP's date function).

    Cheers & thanks for this great lib, Frank

    closes: #148

    opened by fboes 6
  • Two digit milliseconds L sometimes returns three digits

    Two digit milliseconds L sometimes returns three digits

    I have a dateformat string that uses L, which should return milliseconds with 2 digits. The full dateformat string is yyyymmddHHMMssL, which should generate a 16 digit string that is then followed by other data - it's used for a filename generator.

    I have a unit test doing a sanity check on this, which checks the presence of 16 digits using regexp.

    Once in a blue moon this test fails because the resulting date format string contains 17 digits. The resulting string this morning was 20180727084011100.

    Is it possible that L gave 100 here because it ended with 00?

    Either way, the expected behaviour is that L should always return two digits as the spec says. I'll change to use l for now.

    opened by ericnordebaeck 5
  • Provide masks DDD and DDDD to print

    Provide masks DDD and DDDD to print "Yesterday", "Today" or "Tomorrow".

    • If the date belongs to yesterday, today or tomorrow the masks should print so.
    • If the date does not lie in these days then DDD should fall back to ddd and DDDD to dddd.
    • Unit tests added
    • Readme updated
    opened by TalhaAwan 5
  • isoUtcDateTime doesn't even come close ...

    isoUtcDateTime doesn't even come close ...

    TypeScript:

    var date: Date = new Date(); var d: string = dateFormat(date, "isoUtcDateTime");

    Yields ... ==> "07/28/2016 16:13:39"

    instead of the "2010-12-08T16:42:48Z" type of format ...

    opened by HoosierMike 4
  • Issue on passing normal text to dateFormat function

    Issue on passing normal text to dateFormat function

    As per README.md description the following code should work:

    // ...Or add your own
    dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
    dateFormat(now, "hammerTime");
    // 17:46! Can't touch this!
    

    But, as I have seen in my app, it does not. So I figured it out that I have to pass the desired text nested in the same type of quote (single ' or double "), with backward slashes, as the one the nests the format it self.

    Example given (double quotes):

    // Now this works
    dateFormat.masks.hammerTime = "HH:MM! \"Can't touch this!\"";
    dateFormat(now, "hammerTime");
    // 17:46! Can't touch this!
    

    So, I have no idea if I'm doing something wrong, but if this is true a real issue that I see is that would be impossible to pass the word can't as normal text when using single quotes...

    opened by brunokrebs 4
  • Library fails for the basic case dateFormat(

    Library fails for the basic case dateFormat("2022-11-10", "mmm dd")

    Even a datestring with no time or timezone info is rendered incorrectly, date is offset.

    See: https://codesandbox.io/s/naughty-lederberg-8dri33?file=/src/index.js

    In the console I see "Nov 09"

    opened by justin-barca-at-camis 0
  • Week number is not always right

    Week number is not always right

    Hi,

    The week number is not always correct. Check this:

      console.log("2022-01-04 = week: " + dateFormat(new Date("2022-01-04"), "W")); // 4 january must be week 1, this is correct
      console.log("2022-01-10 = week: " + dateFormat(new Date("2022-01-10"), "W")); // monday next week
      console.log("2022-01-17 = week: " + dateFormat(new Date("2022-01-17"), "W"));
      console.log("2022-01-24 = week: " + dateFormat(new Date("2022-01-24"), "W"));
    

    When I set my timezone to Fuji (UTC+12:00) it prints out:

    2022-01-04 = week: 1
    2022-01-10 = week: 2
    2022-01-17 = week: 2
    2022-01-24 = week: 3
    

    It prints two times week 2. This is not correct. Can you fix this? Or am I wrong?

    Thanks! Olaf

    opened by Olafxso 1
  • dateformat not working with

    dateformat not working with "require" ?

    using import I get this error SyntaxError: Cannot use import statement outside a module while using require this error

    Error [ERR_REQUIRE_ESM]: require() of ES Module /var/www/html/wikisphere-nodejs/node_modules/dateformat/lib/dateformat.js from /var/www/html/wikisphere-nodejs/fetch.js not supported.
    Instead change the require of dateformat.js in /var/www/html/wikisphere-nodejs/fetch.js to a dynamic import() which is available in all CommonJS modules.
        at Object.<anonymous> (/var/www/html/wikisphere-nodejs/fetch.js:30:18) {
      code: 'ERR_REQUIRE_ESM'
    

    any hint ?

    (node v16.13.0 npm 8.1.0)

    opened by thomas-topway-it 7
  • token export

    token export

    Any reason to have this error in version 5

    /home/luissilva/pool/node_modules/dateformat/lib/dateformat.js:26 export default function dateFormat (date, mask, utc, gmt) { ^^^^^^

    SyntaxError: Unexpected token export at Module._compile (internal/modules/cjs/loader.js:760:23) at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10) at Module.load (internal/modules/cjs/loader.js:685:32) at Function.Module._load (internal/modules/cjs/loader.js:620:12) at Module.require (internal/modules/cjs/loader.js:723:19) at require (internal/modules/cjs/helpers.js:14:16) at Object. (/home/luissilva/pool/lib/logger.js:11:18) at Module._compile (internal/modules/cjs/loader.js:816:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10) at Module.load (internal/modules/cjs/loader.js:685:32)

    opened by maletazul 1
Releases(v5.0.3)
Owner
Felix Geisendörfer
Felix Geisendörfer
A repository with the purpose of Node.js streams study. Powered by JS Expert Week / @ErickWendel

Spotify Radio - Semana JS Expert 6.0 Seja bem vindo(a) à sexta Semana Javascript Expert. Este é o código inicial para iniciar nossa jornada. Marque es

Osman Rodrigues 9 Oct 28, 2022
A CJS version of dateformat, forked from node-dateformat

dateformat A node.js package for Steven Levithan's excellent dateFormat() function. This module was forked from https://github.com/felixge/node-datefo

Matteo Collina 14 Sep 25, 2021
Demo for my talk "Stream Away the Wait" – a talk about making excellent pending experiences.

?? Stream Away the Wait When implementing the design of a user interface, we often finish before remembering that not everyone's running the app's ser

Kent C. Dodds 25 Nov 1, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil ?? A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Ben Smith 21 Jun 20, 2022
Tries to execute sync/async function, returns a specified default value if the function throws

good-try Tries to execute sync/async function, returns a specified default value if the function throws. Why Why not nice-try with it's 70+ million do

Antonio Stoilkov 14 Dec 8, 2022
Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Jarred Sumner 19 Dec 19, 2022
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
Multi-platform node package bundle to a package.json.

dmpc Multi-platform node package bundle to a package.json. install ### npm mode npm i -g @kingsword/dmpc ### yarn mode yarn global add @kingsword/dmp

Kingsword 2 Oct 16, 2022
A NodeJS package for voice channel interactions on Revolt. This package lets you join voice channels, play music and more!

Revoice.js - A Voice Module for Revolt This package is still in developement and lacks many features. You still are able to play sound to a voice chan

ShadowLp174 13 Dec 25, 2022
An NPM package to help frontend developers get started with using SASS and SCSS on your project easily. The Package follows the 7-1 architecture project structure.

Project Title - Create SASS APP Ever wanted to code up a frontend project with SASS & SCSS and you are stuck with building the acclaimed 7-1 architect

Kelechi Okoronkwo 7 Sep 22, 2022
This package is for developers to be able to easily integrate bad word checking into their projects.\r This package can return bad words in array or regular expression (regex) form.

Vietnamese Bad Words This package is for developers to be able to easily integrate bad word checking into their projects. This package can return bad

Nguyễn Quang Sáng 8 Nov 3, 2022
A template repository / quick start to build Azure Static Web Apps with a Node.js function. It uses Vue.js v3, Vue Router, Vuex, and Vite.js.

Azure Static Web App Template with Node.js API This is a template repository for creating Azure Static Web Apps that comes pre-configured with: Vue.js

Marc Duiker 6 Jun 25, 2022
100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

alloc 54 Dec 29, 2022
Node js package makes creating node jd dependincies files like Controllers,Entities and Repositories easier by executing a few instructions

Nodejs Studio Node js package makes creating node js project dependincies files like Controllers,Entities and Repositories easier by executing a few i

Syrian Open Source 9 Oct 12, 2022
A React utility belt for function components and higher-order components.

A Note from the Author (acdlite, Oct 25 2018): Hi! I created Recompose about three years ago. About a year after that, I joined the React team. Today,

Andrew Clark 14.8k Jan 4, 2023
JSCover is a JavaScript Code Coverage Tool that measures line, branch and function coverage

JSCover - A JavaScript code coverage measurement tool. JSCover is an easy-to-use JavaScript code coverage measuring tool. It is an enhanced version of

null 392 Nov 20, 2022