Giter Club home page Giter Club logo

fecha's Introduction

fecha Build Status

Lightweight date formatting and parsing (~2KB). Meant to replace parsing and formatting functionality of moment.js.

NPM

npm install fecha --save

Yarn

yarn add fecha

Fecha vs Moment

Fecha Moment
Size (Min. and Gzipped) 2.1KBs 13.1KBs
Date Parsing
Date Formatting
Date Manipulation
I18n Support

Use it

Formatting

format accepts a Date object (or timestamp) and a string format and returns a formatted string. See below for available format tokens.

Note: format will throw an error when passed invalid parameters

import { format } from 'fecha';

type format = (date: Date, format?: string, i18n?: I18nSettings) => str;

// Custom formats
format(new Date(2015, 10, 20), 'dddd MMMM Do, YYYY'); // 'Friday November 20th, 2015'
format(new Date(1998, 5, 3, 15, 23, 10, 350), 'YYYY-MM-DD hh:mm:ss.SSS A'); // '1998-06-03 03:23:10.350 PM'

// Named masks
format(new Date(2015, 10, 20), 'isoDate'); // '2015-11-20'
format(new Date(2015, 10, 20), 'mediumDate'); // 'Nov 20, 2015'
format(new Date(2015, 10, 20, 3, 2, 1), 'isoDateTime'); // '2015-11-20T03:02:01-05:00'
format(new Date(2015, 2, 10, 5, 30, 20), 'shortTime'); // '05:30'

// Literals
format(new Date(2001, 2, 5, 6, 7, 2, 5), '[on] MM-DD-YYYY [at] HH:mm'); // 'on 03-05-2001 at 06:07'

Parsing

parse accepts a Date string and a string format and returns a Date object. See below for available format tokens.

NOTE: parse will throw an error when passed invalid string format or missing format. You MUST specify a format.

import { parse } from 'fecha';

type parse = (dateStr: string, format: string, i18n?: I18nSettingsOptional) => Date|null;

// Custom formats
parse('February 3rd, 2014', 'MMMM Do, YYYY'); // new Date(2014, 1, 3)
parse('10-12-10 14:11:12', 'YY-MM-DD HH:mm:ss'); // new Date(2010, 11, 10, 14, 11, 12)

// Named masks
parse('5/3/98', 'shortDate'); // new Date(1998, 4, 3)
parse('November 4, 2005', 'longDate'); // new Date(2005, 10, 4)
parse('2015-11-20T03:02:01-05:00', 'isoDateTime'); // new Date(2015, 10, 20, 3, 2, 1)

// Override i18n
parse('4 de octubre de 1983', 'M de MMMM de YYYY', {
  monthNames: [
    'enero',
    'febrero',
    'marzo',
    'abril',
    'mayo',
    'junio',
    'julio',
    'agosto',
    'septiembre',
    'octubre',
    'noviembre',
    'diciembre'
  ]
}); // new Date(1983, 9, 4)

i18n Support

import {setGlobalDateI18n} from 'fecha';

/*
Default I18n Settings
{
  dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'],
  dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  amPm: ['am', 'pm'],
  // D is the day of the month, function returns something like...  3rd or 11th
  DoFn(dayOfMonth) {
    return dayOfMonth + [ 'th', 'st', 'nd', 'rd' ][ dayOfMonth % 10 > 3 ? 0 : (dayOfMonth - dayOfMonth % 10 !== 10) * dayOfMonth % 10 ];
  }
}
*/

setGlobalDateI18n({
  dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'],
  dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  amPm: ['am', 'pm'],
  // D is the day of the month, function returns something like...  3rd or 11th
  DoFn: function (D) {
    return D + [ 'th', 'st', 'nd', 'rd' ][ D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10 ];
  }
});

Custom Named Masks

import { format, setGlobalDateMasks } from 'fecha';
/*
Default global masks
{
  default: 'ddd MMM DD YYYY HH:mm:ss',
  shortDate: 'M/D/YY',
  mediumDate: 'MMM D, YYYY',
  longDate: 'MMMM D, YYYY',
  fullDate: 'dddd, MMMM D, YYYY',
  shortTime: 'HH:mm',
  mediumTime: 'HH:mm:ss',
  longTime: 'HH:mm:ss.SSS'
}
*/

// Create a new mask
setGlobalDateMasks({
  myMask: 'HH:mm:ss YY/MM/DD';
});

// Use it
format(new Date(2014, 5, 6, 14, 10, 45), 'myMask'); // '14:10:45 14/06/06'

Formatting Tokens

Token Output
Month M 1 2 ... 11 12
MM 01 02 ... 11 12
MMM Jan Feb ... Nov Dec
MMMM January February ... November December
Day of Month D 1 2 ... 30 31
Do 1st 2nd ... 30th 31st
DD 01 02 ... 30 31
Day of Week d 0 1 ... 5 6
ddd Sun Mon ... Fri Sat
dddd Sunday Monday ... Friday Saturday
Year YY 70 71 ... 29 30
YYYY 1970 1971 ... 2029 2030
AM/PM A AM PM
a am pm
Hour H 0 1 ... 22 23
HH 00 01 ... 22 23
h 1 2 ... 11 12
hh 01 02 ... 11 12
Minute m 0 1 ... 58 59
mm 00 01 ... 58 59
Second s 0 1 ... 58 59
ss 00 01 ... 58 59
Fractional Second S 0 1 ... 8 9
SS 0 1 ... 98 99
SSS 0 1 ... 998 999
Timezone Z -07:00 -06:00 ... +06:00 +07:00
ZZ -0700 -0600 ... +0600 +0700

fecha's People

Contributors

9y5 avatar amoilanen avatar balloob avatar dependabot[bot] avatar dettier avatar fer22f avatar james1293 avatar jorrit avatar pmwmedia avatar remi avatar rohmanhm avatar sobolevn avatar taylorhakes avatar troy351 avatar ur5us avatar yanyuanfe avatar zlepper avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fecha's Issues

Support for timezone names

Hey,

Can you please add support for timezone names such as GMT, UTC, EST, BST and so on?

I really love your library and the fact that is so small and performant and that would help me greatly to parse logs from various servers around the world.

Thank you!

Better Error Handling for Bad Format

I mistakenly passed in a bad format 'YYY-MM-DD' (year was supposed to be 'YYYY') to the parse function. Took me a little to debug. Perhaps throwing an error here might help:

fecha/src/fecha.js

Lines 292 to 295 in 50fdd35

var matches = dateStr.match(new RegExp(newFormat, 'i'));
if (!matches) {
return null;
}

Maybe something like: "Date string does not fit format" ?

Adding n days

Is it possible to output 2 date values, first will be the date & time fecha was executed and then the other output is the date & time plus 3 days?

Allow extending formatting tokens

It would be great if formatting tokens can be extensible. For my use case, I want a token for showing year, only if it's not equal to the current year. Other tokens can be relative time (e.g. 3 minutes ago). I don't know if the implementation allows such extensibility but it would be nice to support such feature.

Should .parse() return `false`?

Hello!
I was trying to make the following instruction and got the following output.

fecha.parse('2015-02-29')
// Sun Mar 01 2015 00:00:00 GMT+0000 (WET)

Souldn't return false instead of the next day?

Fecha 3.0.2 breaks unit tests with TypeScript

I'm trying to migrate from fecha 2.3.3 to version 3.0.2. For my application itself, the new version works perfectly. However, I'm not able to run any unit tests that uses fecha directly or indirectly.

I created a minimal TypeScript project for demonstrating the issue:

src/example.ts

import fecha from "fecha"; // import * as fecha from "fecha" for version 2.3.3
export function output() { return fecha.format(new Date(), "YYYY"); }

src/app.ts

import {output} from "./example";
console.log(output());

src/app.test,ts

import {output} from "./example";
it("output", () => expect(output()).toEqual("2019"));

package.json

{
	"private": true,
	"dependencies": {
		"fecha": "3.0.2"
	},
	"devDependencies": {
		"@types/jest": "23.3.12",
		"awesome-typescript-loader": "5.2.1",
		"jest": "23.6.0",
		"ts-jest": "23.10.5",
		"typescript": "3.2.2",
		"webpack": "4.28.3",
		"webpack-cli": "3.2.1"
	},
	"jest": {
		"preset": "ts-jest"
	}
}

tsconfig.json

{ "include": [ "./src/" ] }

webpack.config.js

module.exports = {
    entry: "./src/app.ts",
    output: { filename: "bundle.js" },
    resolve: { extensions: [".ts"] },
    module: { rules: [ { test: /\.ts$/, use: { loader: "awesome-typescript-loader" } } ] }
}

I can compile (yarn run webpack -p) and execute the bundle (node ./dist/bundle.js) successfully.

However, when I try to run the tests (yarn run jest), I get an error:

 FAIL  src/app.test.ts
  × output (7ms)

  ● output

    TypeError: Cannot read property 'format' of undefined

      1 | import fecha from "fecha";
    > 2 | export function output() { return fecha.format(new Date(), "YYYY"); }
        |                                         ^

      at Object.output (src/example.ts:2:41)
      at Object.<anonymous> (src/app.test.ts:4:27)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.074s, estimated 3s
Ran all test suites.
error Command failed with exit code 1.

The same error occurs also with other testing frameworks like Jasmine. With fecha 2.3.3, it had worked.

Wrong Formated Date

Format method is not formatting the date correctly

fecha.format(new Date(2019, 12, 31), 'MM/DD/YYYY')

returns 01/31/2020 instead of 12/31/2019

Es modules version

It seems like the module version is not published.
image

Is there any chance to publish it?

Thanks.

Typescript typings are not published to npm

Very nice to see that typescript typings are available, sadly for people to be able to consume these, they need to be published to npm, together with the rest of the fecha bundle.

type define is not valid

current is:

export function format(dateObj: Date | number, mask: string, i18nSettings?: i18nSettings): string;
export function parse(dateStr: string, format: string, i18nSettings?: i18nSettings): Date | null;

should be:

type Fecha = {
  format: (dateObj: Date | number, mask: string, i18nSettings?: i18nSettings): string;
  parse: (dateStr: string, format: string, i18nSettings?: i18nSettings): Date | null;
}

export default Fecha;

Feature request: Support microseconds in timestamp format

Winston@3, AWS Linux instance, Javascript

What's the feature?
Add microseconds precision to the timestamp format. something like:
timestamp({ format: 'YYYY-MM-DD HH:mm:ss.' })

What problem is the feature intended to solve?
My use case is logging (I'm using Winston which in turn is using fecha under the hood for timestamp formatting). Log aggregation of logs created by many instances of different microservices requires a precision level higher than milliseconds in order to better sort the logs based on their timestamp.

Is the absence of this feature blocking you or your team? If so, how?
Not a blocker, but a very desirable feature.

Is this feature similar to an existing feature in another tool?
No that I know of.

Is this a feature you're prepared to implement, with support from us?
I'd be willing to look into it.

Add Z formatting token

Currently fecha supports the ZZ formatting token, but it would be nice if we also had Z which is defined in moment:

Token Output
Z -07:00 -06:00 ... +06:00 +07:00
ZZ -0700 -0600 ... +0600 +0700

I came across this issue because js-joda currently doesn't parse it without the colon (js-joda/js-joda#377).

EDIT: RFC3339 requires the colon, so yea, we do need this.

How to set a locale

Is it possible to set a custom locale? If user has the browser's language set to english he might change the website's language to another language. How can I set a custom locale when formatting the date using Fecha?

Snitram

Literals not working in minified version

Really weird but it stripped out all reference to the literals (eg: 'D MMM YYYY [at] h:mma') so that it was outputting [pmt] or [amt] using the 'a' as a token... I took the fecha.js file over to an online minifyer and it worked fine... Can you guys please correct this and push the working 'official' min.js file to git.

Cheers!
Richard :o)

unix timestamp format support

I may have missed it, but is there a way to format("x") or format("unix") to return the date as a unix timestamp?

fecha.format force specific timezone

Hi,

It's possible to add tjhe possibility to force the format function with specific timezone ?

Actually, If I pass an UTC date in my brwoser, the formatted date is converted into the local timezone (Europe/Paris).

But, I want show the date in UTC format (or get a part of this date in the UTC timezone like juste the hour part).

Thanks

fecha.format doesn't print 4-digit year for YYYY

I don't know if it's a bug or feature, but I was depending on fecha to set date-part to HTML5 date input, which expects date in format YYYY-MM-DD, where YYYY means 4-digit year.

However, fecha substitutes YYYY with Date.getFullYear() which is as long as it takes...

So the following code:

var date = new Date('0999-10-09T22:00:00.000Z');
console.log(fecha.format(date, 'YYYY-MM-DD'));

Produces "999-10-10" instead of "0999-10-10".

Is it intended behavior?

Error with UMD pattern

I get a wild error when I import the library with RequireJS, I see that evaluate require instead of define in the UMD pattern

if (typeof module !== 'undefined' && module.exports) {
    module.exports = fecha;
} else if (typeof require !== 'undefined' && require.amd) {
    define(function () {
        return fecha;
    });
} else {
    main.fecha = fecha;
}

...

define(['bower_components/fecha/fecha'], function(fecha) {
    typeof fecha === 'undefined'; // true
    typeof window.fecha === 'undefined'; // true
    window.fecha.parse('2015-01-01'); // it's works
    fecha.parse('2015-01-01'); // error
});

whit define instead of require

if (typeof module !== 'undefined' && module.exports) {
    module.exports = fecha;
} else if (typeof define !== 'undefined' && define.amd) {
    define(function () {
        return fecha;
    });
} else {
    main.fecha = fecha;
}

...

define(['bower_components/fecha/fecha'], function(fecha) {
    typeof fecha === 'undefined'; // false
    typeof window.fecha === 'undefined'; // true
    // window.fecha.parse('2015-01-01'); // error
    fecha.parse('2015-01-01'); // it's works
});

fecha.parse gives me a wrong value.

see snippet:

fecha.parse = function (dateStr, format) {
    var time, isValid, dateInfo, today, date, info, index;

    if (!format) {
        time = Date.parse(dateStr.replace(/\-/g, '/'));
        if (!isNaN(time)) {
            return new Date(time);
        } else {
            return false;
        }

    } else {

I have tried the following code on both Chrome and Safari:

Date.parse("2015-07-18T07:53:14.000Z")
// 1437205994000
Date.parse("2015/07/18T07:53:14.000Z")
// NaN

As you can see, after replace '-' to '/', Date.parse cannot parse the date string correctly, then the function gives me 'false'.

The javascript document says:

Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return NaN.

Obviously, the "2015-07-18T07:53:14.000Z" is legal while "2015/07/18T07:53:14.000Z" is illegal.

I don't know why you must change - to /.

Conditional params / i.e. year

Hi,

is there a way to display year part of the date only when the year is not the current year?

example:
Jan 27
but: Dec 31, 2016

Literal support in formatting mask

moment.js allows to use literals in formatting masks, it would be nice to have a similar feature in fecha.

Example:

fecha.format(new Date(2001, 2, 5, 6, 7, 2, 5), '[on] MM-DD-YYYY [at] HH:mm');
// 'on 03-05-2001 at 06:07'

PR that implements the feature #17

Timezone here in Brazil is wrong(correct is -3)

const fecha = require('fecha');
console.log(fecha.format(new Date(), 'hh:mm'));

Example:
Time now: 05:00 - right
fecha.format: 06:00 - wrong

Daylight Saving Time has been permanently abolished in Brazil, according to the Senate bulletin of April 25, 2019.

Add i18n as 3rd param

Add i18n settings as 3rd param to fecha.parse and fecha.format. This would allow people to change i18n settings without doing it globallly on fecha.i18n. fecha.i18n will still be available for global changes.

Add info how to import library into the readme file

Hello

Thank you for this lightweight library, I really like it.
I found that there is no info on how to import it.
It's quite obvious for an experienced developer, but let's make it simple for newbies also.

I've prepared a simple MR, could you check it? If you will approve, please don't forget to update it on the page of the project for NPM, because most of the people open the page of the project there.

MR: #68

Timezone issues

I have tested the parse method for different time zones and see that

parse('1990-01-01', 'YYYY-MM-DD')

returns null when in the Lima/Peru timezone. I have modified the test for the first day of month for 1st of January 1990 and this is the output of the test

x first day of the month
expected 0 to equal 631170000000

I did it on a Ubuntu 18.04 VM but cannot reproduce the error on more negative timezones.

fecha.parse method is allowing an invalid and a malformed dates

I'd expected to get a false return or an exception when I called the fecha.parse method with an invalid and a malformed dates. But it parsed them successfully. Is this the desired result?

Invalid: Date parts are not in the valid ranges (12 >= Month >= 1, 31>= Day>= 1, 23>=Hour>= 0 ...)

fecha.parse('2016-44-99', 'YYYY-MM-DD'); // Sat Nov 12 2016 21:39:00 GMT+0300
fecha.parse('2016-11-11 44:44', 'YYYY-MM-DD HH:mm'); // Sat Nov 12 2016 20:44:00 GMT+0300

Malformed: Supplied date string does not match the format

fecha.parse('2016-1-1', 'YYYY-MM-DD'); // Fri Jan 01 2016 01:00:00 GMT+0400
fecha.parse('2016-11-11 3:4', 'YYYY-MM-DD HH:mm'); // Fri Nov 11 2016 03:04:00 GMT+0300

Invalid & Malformed:

fecha.parse('2016-9876-123', 'YYYY-MM-DD'); // Tue Apr 16 2024 00:00:00 GMT+0300
fecha.parse('2016-11-11 4433:3344', 'YYYY-MM-DD HH:mm'); // Sat Nov 12 2016 20:33:00 GMT+0300

Tested on: Google Chrome Version 54.0.2840.71 m (Windows 10)

Thanks,

No map file in npm version

It seems lib/fecha.js.map and lib/fecha.umd.js.map were not inside node_modules.
But at the end of file lib/fecha.js did linked to the map file.

//# sourceMappingURL=fecha.js.map

This makes error when I using vite
image

Zero based dates

First up, awesome library. Thanks for all the hard work.

This is more of a usability/understandability issue. Right now dates are being parsed 0 based. This means that the following happens

fecha.parse('2010-02-02', 'YYYY-MM-DD');// 02 March 2010
fecha.parse('2010-03-02', 'YYYY-MM-DD');// 02 April 2010
fecha.parse('2010-04-02', 'YYYY-MM-DD');// 02 May 2010

The documentation seems to suggest that this is expected behavior

fecha.parse('10-12-10 14:11:12', 'YY-MM-DD HH:mm:ss'); // new Date(2010, 11, 10, 14, 11, 12)

As you can imagine this is a land mine for a any developer (including myself) that didn't read the fine print.
My recommendation is that is should parse the dates non-zero based so that its more predictable

Timezone tokens Z and ZZ works wrong

Token 'Z' produces 'Z' as an output (i.e. it is not recognized).

Token 'ZZ" produces time offset without ::

console.log(fecha.format(new Date("2017-03-11T02:30:00.000+07:00"), "ZZ"));
// +0100

It also uses current machine timezone. Because new Date().getTimezoneOffset(); always returns current machine timezone.

fecha version 4.1.0 .

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.