knowledgecode / date-and-time Goto Github PK
View Code? Open in Web Editor NEWA Minimalist DateTime utility for Node.js and the browser
License: MIT License
A Minimalist DateTime utility for Node.js and the browser
License: MIT License
Hi!
I'm seeing some odd behavior with isValid() and parse(), probably associated with the regEx for the input format:
console.log(Dates.isValid('31/12/1985', 'humbug')); // false 👍
console.log(Dates.isValid('31/12/1985', 'foo')); // true 😞
console.log(Dates.isValid('31/12/1985', 'bar')); // true 😞
console.log(Dates.isValid('31/12/1985', 'boom')); // true 😞
console.log(Dates.isValid('31/12/1985', 'spazz')); // true 😞
console.log(Dates.parse('31/12/1985', 'spazz')); // Thu Jan 01 1970 00:00:31 GMT-0500 (EST)
Hey there,
I am not able to change the locale to 'de' with version 1.0.0.
import DateTime from 'date-and-time';
DateTime.locale('de');
console.log(DateTime.locale()); // => still "en"
const {format} = DateTime;
{format(new Date(), 'ddd DD. MMM YYYY')} // instead of "Di" it says "Thu"
Can you reproduce this?
does it support Jalali date?
I'm used to import your (nice) lib like this:
import DateTime from 'date-and-time'
However, after I've updated to 0.11. I get this warning:
export 'default' (imported as 'DateTime') was not found in 'date-and-time'
Did you remove this intentionally or accidentally?
When providing a time string of 2022-02-22T14:00:00.000+1200 and a time format of YYYY-MM-DD[T]HH:mm:ss.SSSZ, formatTZ will succeed.
When providing a time string of 2022-02-22T14:00:00.000+1300 with the same time format, formatTZ will fail with RangeError: Invalid time value.
This might be due to NZDT (New Zealand Daylight Time) being forgotten and the range of "Z" only goes up to 12
Hi
I'm having some trouble parsing strings with six millisecond digits using .parse()
.
The strings look like this: 2019-11-13T10:22:16.866122Z
2019-11-11T10:23:23.392706Z
I've tried these formats:
"YYYY-MM-DDTHH:mm:ss.SSSSSSZ" (not listed as a supported format)
"YYYY-MM-DDTHH:mm:ss.SSSZ" (listed as a supported format for 3 ms digits)
"YYYY-MM-DDTHH:mm:ss"
If the string is shortened to 2019-11-13T10:22:16Z
, the format YYYY-MM-DDTHH:mm:ssZ
works just fine.
Also, if the string is shortened to just 3 millisecond digits 2019-11-13T10:22:16.866Z
, the format YYYY-MM-DDTHH:mm:ss.SSSZ
works just fine.
To play with it you can use https://npm.runkit.com/date-and-time
and paste in this:
var dateAndTime = require("date-and-time")
var timestamp = "2019-11-13T10:22:16.866122Z";
var res = dateAndTime.parse(timestamp, "YYYY-MM-DDTHH:mm:ss.SSSSSSZ");
console.log(res);
consider following code:
const date_and_time = require('date-and-time')
const d = new Date(Date.UTC(2022,2,1)) // 1st of March
const nextMonth = date_and_time.addMonths(d, 1) // nextMonth should be 1st of April
console.log(nextMonth)
yields
2022-03-31T23:00:00.000Z
tested on Node v18, MacOS, German locale.
Hi,
I've noticed that parsing requires quite a bit of computation, with regex's and parsing; based on my own performance benchmarking of my code; I can see the parse call contributes about 35% of my Javascript code's running time.
I was wondering if you could please see what you can do to better do precomputation. For example, for parsing, the string format is usually known upfront; and can be "precomputed" into the data structures you would need; so you can do your translations later.
There may be other ideas, but this is one that comes to mind.
Thanks,
Ronak
I have updated the RN version 0.69.1. Getting below error when execute command 'pod install'.
Error:
'Invalid Podfile
file: 767: unexpected token at 'Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './package.json' is not defined by "exports" in /…/node_modules/date-and-time/package.json'
Why date.parse('15/10/2017', 'DD/MM/YYYY') = NaN ?
There was a missing 'D' in your time parser for some reason, just wanted to point it ou to you.
Hello! Please, change days of week in ru locale:
"dddd: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота']"
Thank you very much!
This may be more of a question, but is there a way to parse the following?:
DECEMBER 10TH 2020
I tried MMMM D[TH] YYYY
but I would get Invalid Date.
If I transformed the input string to December 10TH 2020
it would successfully parse the date.
Any guidance would be greatly appreciated!
If this currently is not supported, I would also think the variations that would be great to support would be any casing of:
Thanks again and great work!
Hey! We had a flawlessly working system and our "working" code suddenly starts giving us Invalid Date
outputs
I have tried code from months back and give the same error
const date = interaction.options.getString("event-date");
console.log(date);
const pattern = datetime.compile("D-M-YYYY h:m A");
let parsedDate = datetime.parseTZ(date, pattern, "Asia/Kolkata");
13-2-2023 9:45 PM
Invalid Date
System Info
NODE - v18.13.0
Linux localhost.localdomain 5.15.85-gentoo-dist #1 SMP Thu Dec 22 12:11:58 -00 2022 x86_64 AMD A8-7410 APU with AMD Radeon R5 Graphics AuthenticAMD GNU/Linux
I have used the danish locale file to make a swedish one.
Here it is:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.date = global.date || {}, global.date.locale = global.date
.locale || {}, global.date.locale.sv = factory()));
})(this, (function () { 'use strict';
/**
* @preserve date-and-time.js locale configuration
* @preserve Swedish (SV)
* @preserve It is using moment.js locale configuration as a reference.
*/
var sv = function (date) {
var code = 'sv';
date.locale(code, {
res: {
MMMM: ['januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december'],
MMM: ['jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
dddd: ['söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag'],
ddd: ['sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör'],
dd: ['sö', 'må', 'ti', 'on', 'to', 'fr', 'lö']
}
});
return code;
};
return sv;
}));
Is it possible to parse ISO 8601 formatted strings?
Example: 2022-05-04T00:00:00.000000Z
2018-07-09T20:52:34.185664+00:00 app[web.1]: /app/node_modules/date-and-time/date-and-time.js:231
2018-07-09T20:52:34.185668+00:00 app[web.1]: return new Date(dateObj.getTime() + milliseconds);
2018-07-09T20:52:34.185670+00:00 app[web.1]: ^
2018-07-09T20:52:34.185671+00:00 app[web.1]:
2018-07-09T20:52:34.185672+00:00 app[web.1]: TypeError: dateObj.getTime is not a function
2018-07-09T20:52:34.185674+00:00 app[web.1]: at Object.date.addMilliseconds (/app/node_modules/date-and-time/date-and-time.js:231:33)
2018-07-09T20:52:34.185675+00:00 app[web.1]: at Object.date.addMinutes (/app/node_modules/date-and-time/date-and-time.js:211:21)
2018-07-09T20:52:34.185676+00:00 app[web.1]: at Object.date.format (/app/node_modules/date-and-time/date-and-time.js:84:22)
The package.json exports
field declares that the browser will always get the ESM version of the library.
Jest v28 with jsdom will honour exports
, but does not babelize files in node_modules. Therefore it will crash if you import this library.
"exports": {
".": {
"browser": "./esm/date-and-time.es.js",
"import": "./esm/date-and-time.mjs",
"require": "./date-and-time.js"
},
}
Run this script:
# install jest and uuid
yarn add jest jest-environment-jsdom date-and-time
# create test scenario
cat << TESTFILE > ./tests.spec.js
test("should import date-and-time without crashing", () => require("date-and-time"));
TESTFILE
yarn jest --env jsdom
non-nodejs CJS code that imports uuid should receive the CJS version of the library.
Is there any way how to correctly parse ISO 8601 date-time string?
This formatter 'YYYY-MM-DDTHH:mm:ss[Z]'
is working fine for it but it also works if the last character is for example 'K'. Is there any solution how to make 'Z' required?
Example:
import * as date from 'date-and-time'
import 'date-and-time/plugin/day-of-week'
date.plugin('day-of-week')
const formatter = 'YYYY-MM-DDTHH:mm:ss[Z]'
const dateTime = '1994-11-05T13:15:30Z'
const dateTime2 = '1994-11-05T13:15:30K'
date.parse(dateTime, formatter, true) // Valid Date
date.parse(dateTime2, formatter, true) // Valid Date - should be Invalid tho
transformTZ doesn't handle timezones with UTC.
Steps to reproduce:
const challongeTimeFormat = date.compile('YYYY-MM-DD[T]HH:mm:ss.SSSZ');
const desiredTimeFormat = date.compile('MMM D h:mmA [GMT]Z');
let initialTimeString = reformatChallongeTime(element.tournament['start_at']);
let finalTime;
try {
finalTime = date.transformTZ(initialTimeString['time'],challongeTimeFormat,desiredTimeFormat,'America/New_York',initialTimeString['UTC']);
}
catch (e){
fs.writeFileSync('G:/Coding Projects/stdout/timeshit.txt','Initial Time String: ' +JSON.stringify(element.tournament['start_at'])+'\nPost Colon Removal: '+JSON.stringify(initialTimeString)+'\nConverted Time Zone: '+JSON.stringify(convertedTimezone)+'\n',{ flag: 'a' });
throw e;
}
initialTimeString values:
{ time: '2022-03-06T16:00:00.000-0600', UTC: false }
{ time: '2022-03-06T23:00:00.000+0100', UTC: false }
{ time: '2022-03-06T22:00:00.000+0000', UTC: true }
Expected output:
"Mar 6 5:00PM GMT-0500" for all
Actual output:
-0600 and +0100 output: "Mar 6 5:00PM GMT-0500"
+0000 output: "Mar 6 11:00PM GMT-0500"
I remember having to set the UTC to true when I was using parse and format in order to state explicitly that the timezone that was being used was +0000. Don't know why it was necessary but that worked. It seems the transformTZ has the same issue but doesn't take the optional UTC variable. So maybe two birds with one stone here.
parse function is case sensitive.
So this example won't work
date.parse('29 jul 1990', 'DD MMM YYYY');
But this one, will work
date.parse('29 Jul 1990', 'DD MMM YYYY');
Shouldn't it be case insensitive? Seems like a simple feature
for(let i=0; i<7; i++) {
console.log(date.format(date.addDays(fromDate,-7*i),'YYYY-MM-DD'));
}
output:
2017-04-07
2017-03-31
2017-03-24
2017-03-17
2017-03-09 -----------error from here
2017-03-02
2017-02-23
This returns NaN right now:
dateAndTime.parse("2019-02-21T07:48:28-0800", "YYYY-MM-DDThh:mm:ssZ");
I'm working around it using this undocumented behavior, which is good enough for me at this point (the formatter's going to remove all the spaces, but in my code there are enough to make it pass):
dateAndTime.parse("2019-02-21T07:48:28-0800", "YYYY-MM-DDThh:mm:ss ");
But I'm wondering if I've misunderstood something. Is that first line supposed to work?
If you already have a date string, but in the wrong time zone, you have to transform, then parse and then format it back in order to get it to the correct timezone. It would be nice if there were a transformTZ option.
Though I understand the use case is rather limited and probably not necessary in most cases. My use case is the API I'm working with gives me a random timezone each time I call it. So I know the format before I even know the time. 🙃
It would just save me an extra parse and format call. If there really isn't a need for it, don't worry about it.
A
for a.m.
and p.m.
is nice but is often abbreviated to am
/ pm
too
a
could work nicely as an option for this perhaps?
The GitHub Security Lab reported a potential security vulnerability (GHSL-2020-349) in your project (knowledgecode/date-and-time). We are approaching 90 days since our initial report and as per our coordinated disclosure policy, we intend to publish a public advisory detailing this issue. If you wish to discuss or further coordinate a response to this issue with the GitHub Security Lab, please contact us at [email protected] within the next 7 days in reference to GHSL-2020-349 and we would love to help you resolve these issues. If not, feel free to close this issue and we will proceed with advisory publication on expiration.
Hi,
Parsing strings "1/1/1", "1/1/01", "1/1/001" with D/M/YYYY format yields 1 Jan 2001 date. That is correct.
However, parsing string "1/1/0001" with D/M/YYYY format should yield 1 January 1 year, however it yields 1 Jan 2001.
So effectively, this is not possible to enter close to Christmas dates :)
date-and-time v. 2.3.1
I'm based in the Netherlands and we have clock change for winter and summer time.
Winter time: UTC+1
Summer time: UTC+2
Source: https://www.timeanddate.com/time/zone/netherlands/amsterdam
Right now when I'm trying to .transform()
time string, the library wrongly assumes that it's winter time.
// Now it is 11:45 May 25th in the Netherlands.
const timeStr = "11:45+02:00";
const timeStrTransformed = date.transform(timeStr, "HH:mmZZ", "HH:mm");
console.log(timeStrTransformed); // 10:45
// but expected 11:45 instead of 10:45
When I use .format()
with date object, it assumes everything correctly.
// Now it is 11:45 May 25th in the Netherlands.
const now = new Date();
const timeStr01 = date.format(now, "HH:mmZZ");
const timeStr02 = date.format(now, "HH:mm");
const timeStr03 = date.transform(timeStr01, "HH:mmZZ", "HH:mm")
console.log(`timeStr01: ${timeStr01}`); // "timeStr01: 11:45+02:00"
console.log(`timeStr02: ${timeStr02}`); // "timeStr02: 11:45"
console.log(`timeStr03: ${timeStr03}`); // "timeStr03: 10:45"
// Expected timeStr03 to be 11:45 as well
I really like this library and would appreciate clock change support for .transform()
Hello!
Please, help me. I include import date from "date-and-time"
within my module which working for frontend (client side).
Without using date.locale('it');
that's all working. But when I added date.locale('it');
there was an error: Cannot find module './locale/it'.
Maybe that don't related with your module, however I hope you can help me.
I validate the user input with date.parse(input, 'DD/MM/YYYY HH:mm')
.
To my surprise, the following inputs are valid:
11/11/1 11:11
11/11/12 11:11
11/11/123 11:11
I would expect only the following one to pass:
11/11/1234 11:11
Is there a format token available to force a 4-digit year?
Can you add the language changes to the latest version installed by npm?
Running the following:
date.format(date.parse('12:40', 'hh:mm'), 'hh:mm A')
the result is: 12:40 "am" instead of "pm".
EDIT: my mistake, it should be:
date.parse('12:40', 'HH:mm')
is valid method does not detect all invalid dates like '-015/11/22'
The current version supports output of a.m. or p.m. when using the A format token
The suggestion is to support output of AM or PM when using a new format token: AA
import date from "date-and-time";
import timezone from "date-and-time/plugin/timezone";
date.plugin(timezone);
import de from "date-and-time/locale/de";
date.locale(de);
const now = new Date();
this.CalendarOptions.weekday = date.format(now, "dddd"); // returns 'Donnerstag'
this.CalendarOptions.weekdayTZ = date.formatTZ(now, "dddd", "Europe/Berlin"); // returns 'Thursday'
When using timezones, I cannot get the german locals weekdays from date.formatTZ.
Is that a bug, or am I missing something?
thanks!
Hello,
In the below examples, both of these dates return with NaN, but their reasons are different. Could you please add more clarity for return values?
1) date.parse('Jam 1 2017', 'MMM D YYYY'); // => NaN
2) date.parse('Feb 29 2017', 'MMM D YYYY'); // => NaN
Thanks for the plugin! Is there a CDN for date-and-time?
I tried to run
date.format(new Date().toLocaleString("en-US", { timeZone: "Asia/Kuala_Lumpur" }), 'DD-MM-YYYY hh:mma', true);
However it returns:
d = date.addMinutes(dateObj, utc ? dateObj.getTimezoneOffset() : 0),
^
TypeError: dateObj.getTimezoneOffset is not a function at Object.date.format (/Users/JKnet/erider-function-source/node_modules/date-and-time/date-and-time.js:156:56) at [stdin]:8:6 at Script.runInThisContext (vm.js:132:18) at Object.runInThisContext (vm.js:309:38) at internal/process/execution.js:77:19 at [stdin]-wrapper:6:22 at evalScript (internal/process/execution.js:76:60) at internal/main/eval_stdin.js:29:5 at Socket.<anonymous> (internal/process/execution.js:198:5) at Socket.emit (events.js:326:22)
Does it mean I cannot give a timezone aware object?
Hello!
I think the regEx for AM/PM in times could use some work as well:
console.log(dateAndTime.parse('11:23 p.m.', 'hh:mm A')) // Thu Jan 01 1970 23:23:00 GMT-0500 (EST)
console.log(dateAndTime.parse('11:23 P.M.', 'hh:mm A')) // NaN
console.log(dateAndTime.parse('11:23 PM', 'hh:mm A')) // NaN
console.log(dateAndTime.parse('11:23 pm', 'hh:mm A')) // NaN
I may submit a PR when I have a second, but just wanted to document it in the meantime. Thank you!
Instead of letting a non-synchronized package (@types/date-and-time) do the job, why don't you just add a "types" definition directly to this package?
It would be far better, it is more comfortable for whom uses the types and, generally, very more reliable.
The @types/date-and-time for instance have not been not updated since two years ago and do not support the plugins
Even if your code is not Typescript code, it is extremely easy to create the types declaration for javascript code https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html and could even be automatized with a github action!
start: Mon Mar 27 2023 00:00:00 GMT+0200 (Central European Summer Time)
end: Mon Apr 10 2023 00:00:00 GMT+0200 (Central European Summer Time)
import date from 'date-and-time';
date.addDays(start, -7);
date.addDays(end, -7);
start: Sun Mar 19 2023 23:00:00 GMT+0100 (Central European Standard Time)
end: Mon Apr 03 2023 00:00:00 GMT+0200 (Central European Summer Time)
start: Mon Mar 20 2023 00:00:00 GMT+0100 (Central European Standard Time)
end: Mon Apr 03 2023 00:00:00 GMT+0200 (Central European Summer Time)
2.4.3
I have issue with safari browser! he is give me NaN from JSON Api format liker "2018-04-01 00:00:00".
This package can solve my problem? I did not try to use yet this package.
May be someone had this problem before?
Any plans to add Typescript typings?
Hi,
Docs say to get current date use new Date(). That's only available in the browser, I'd like to get the current date via the server. Is there a method to achieve this?
Due to the specification that each plugin and locale can change the default behavior, importing multiple plugins or changing locales can cause unexpected behavior. To resolve this issue, we would have to accept changes to the plugin and locale specifications.
For instance:
With these changes, some of the existing plugins will be modified or deprecated.
const date = require('date-and-time');
let d = date.parse('Dec, 25 2019 at 3:51 AM', 'MMM, D YYYY at h:m A');
//same error with following line also
//let d = date.parse('Dec, 25 2019 at 3:51 AM', 'MMM, D YYYY at h:m AA (*)');
console.log(d);
output:
Invalid Date
Problem
Current instructions suggest doing the following:
npm i date-and-time
import date from 'date-and-time';
I have a date in Spanish given in the following format: 26 de junio de 2015
.
I would like to have ability to escape non-date symbols which can be confused with date tokens.
For example, how it's done in moment.js: D [de] MMMM [de] YYYY
.
Parsing of "1/1/1" with format "DD/MM/Y" results to 1/1/1901 year, what is difficult to explain to end user.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.