Compare commits

...

26 Commits

Author SHA1 Message Date
Daniel Legt c0f43b21af Logo Update 2022-05-09 21:45:00 +03:00
Daniel Legt 3c63b9cc5b + Versioning 2022-05-08 10:30:17 +03:00
Daniel Legt 5eac2dc1e2 + Readme Update 2022-05-08 10:30:07 +03:00
Daniel Legt 2fca2d3f18 * Versioning 2022-05-08 10:23:49 +03:00
Daniel Legt 3b935ba99e * Changed keywords 2022-05-08 10:23:26 +03:00
Daniel Legt 8ca22248c1 + Readme Images 2022-05-07 15:34:40 +03:00
Daniel Legt d2f72cdb6e * Updated Dependencies 2022-05-07 15:18:48 +03:00
Daniel Legt c7694ad02c + Versioning 2022-05-07 15:17:21 +03:00
Daniel Legt f32ac70832 + ReadME Updates 2022-05-07 15:16:53 +03:00
Daniel Legt 2e55071179 Still trying to fix this mess 2022-05-07 15:10:36 +03:00
Daniel Legt 3a9ccf83b5 Fixed NPM Package 2022-05-07 15:07:08 +03:00
Daniel Legt dc77be9a2d Versioning 2022-05-07 15:05:19 +03:00
Daniel Legt 6ce817ab1b + A lot of distribution Work 2022-05-07 15:04:19 +03:00
Daniel Legt afe37e1f78 + Tests 2022-05-07 14:35:15 +03:00
Daniel Legt 04dc772e05 + Seconds Handler 2022-05-07 14:28:26 +03:00
Daniel Legt 5b71124dde + Parsing for Minutes 2022-05-07 14:26:05 +03:00
Daniel Legt 3cd34ad28a * Comments 2022-05-07 14:24:25 +03:00
Daniel Legt 89105840cc + Hour Added
* Fixed Types
2022-05-07 14:22:36 +03:00
Daniel Legt 48a6d18c24 * Moved Tests
+ Declare all new Types
2022-05-07 14:11:24 +03:00
Daniel Legt 97aa3e2281 + Versioning 2022-05-07 14:03:22 +03:00
Daniel Legt d97a80bb39 First version of the working date formatter 2022-05-07 14:02:55 +03:00
Daniel Legt 8d3de497e9 . 2022-05-07 13:54:58 +03:00
Daniel Legt 91c4a86757 Versioning 2022-05-07 13:50:43 +03:00
Daniel Legt a88351922f * Changed the valid inputs to actually conform to a standard
* Fixed a bunch of bugs
+ Year
2022-05-07 13:49:57 +03:00
Daniel Legt c596812d30 Days implementation
+ getDate
+ dayTypes
2022-05-06 01:07:13 +03:00
Daniel Legt 1112a92023 + License 2022-05-06 00:48:33 +03:00
18 changed files with 7617 additions and 34 deletions

4
.gitignore vendored
View File

@ -1,5 +1,5 @@
node_modules node_modules
package-lock.json lib
dist/* dist/*
!dist.keep !dist/.keep

2
.npmignore Normal file
View File

@ -0,0 +1,2 @@
src
tsconfig.json

0
CONTRIBUTING.md Normal file
View File

View File

@ -1 +1,90 @@
# Tyme.js ![Tyme.JS](./logo.png)
[Site](https://justkato.me/) |
[Docs/Wiki](https://github.com/JustKato/Tyme.js/wiki) |
[Contributing](CONTRIBUTING.md) |
Building the project yourself:
```shell
$ git pull https://github.com/JustKato/Tyme.js tymejs
$ cd tymejs
$ npm run build
```
## Download
[![Web Download](https://img.shields.io/badge/Web-Download%20Package-yellow?style=for-the-badge&logo=javascript)](https://github.com/JustKato/Tyme.js/releases/download/3.0.0/tyme.js-3.0.0.zip.zip)
[![NPM Download](https://img.shields.io/badge/NPM-Download-orange?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/tymejs)
Tyme.js is released under the [MIT license](license) & supports modern environments.<br>
## Installation
In a browser:
```html
<script src="tyme.js"></script>
```
Using npm:
```shell
$ npm i tymejs
```
## Usage
All of the available formats are directly from [PHP's date formats](https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters)
#### ⚠ Warning ⚠
⚠ Not all different character formats have been implemented. ⚠
In Node.js TypeScript:
```js
// Import the Package
import TymeJS from "tymejs"; // Use require for plain javascript
// Get the date object from Somewhere
let myDate: Date = new Date();
// Initialize the TymeJS Object
let t: TymeJS = new TymeJS(myDate);
// Now you can format different dates
let formattedDate: string = t.format("d/m/Y H:i A");
// All Available formats: https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters
// Log the formatted Date
console.log(formattedDate);
```
In Node.js using JavaScript:
```js
const { default: TymeJS } = require("tymejs");
// Get the date object from Somewhere
let myDate = new Date();
// Initialize the TymeJS Object
let t = new TymeJS(myDate);
// Now you can format different dates
let formattedDate = t.format("d/m/Y H:i A");
// All Available formats: https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters
// Log the formatted Date
console.log(formattedDate);
```
## Why TymeJS?
TymeJS makes working with JavaScript date objects much easier, I've found myself<br>
multiple times in the situation where the client doesn't like their region's date format
and requests for custom formats, this consumed a lot of time implementing, so that's why
I have created this library, for:
* Reliable Date formats
* Reliable Time formats
* TypeScript Support

0
dist/.keep vendored Normal file
View File

7
jestconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"transform": {
"^.+\\.(t|j)sx?$": "ts-jest"
},
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"]
}

21
license Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) [2022] [Kato Twofold]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

7164
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,18 +1,36 @@
{ {
"name": "tymejs", "name": "tymejs",
"version": "0.1.0", "version": "0.4.5",
"description": "Quickly and easily format JavaScript date Objects", "description": "Quickly and easily format JavaScript date Objects",
"main": "dist/index.js", "main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": { "scripts": {
"build": "esbuild src/index.ts --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 --outfile=dist/tyme.js", "build": "tsc",
"test": "tsc" "buildweb": "esbuild src/index.ts --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 --outfile=dist/tyme.js",
"test": "jest --config jestconfig.json"
}, },
"keywords": [ "keywords": [
"time", "time",
"time format",
"date", "date",
"date", "date format",
"datetime",
"datetime format",
"format" "format"
], ],
"author": "Kato Twofold", "author": "Kato Twofold",
"license": "MIT" "license": "MIT",
"repository": {
"url": "https://github.com/JustKato/Tyme.js"
},
"devDependencies": {
"@types/jest": "^27.5.0",
"jest": "^28.1.0",
"ts-jest": "^28.0.1",
"typescript": "^4.6.4",
"ts-node": "^10.7.0"
},
"files": [
"lib/**/*"
]
} }

View File

@ -0,0 +1,17 @@
/**
* A dictionary for all of the days of the week
*/
const dayDictionary: Array<string> = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
export {
dayDictionary
};

View File

@ -1 +1,67 @@
export type monthType = "single" | "double" | "short" | "full" // All mappings according to: https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters
// ############################## [ Common Formats ] ##############################
export type commonDateFormats = "d/m/Y" | "m/d/Y" | "d/m/Y h:i A" | "d/m/Y H:i" | "m/d/Y h:i A" | "m/d/Y H:i";
// ############################## [ Time Formats ] ##############################
// =-=-=-=-=-=-=-=-=-=-= [ Meridiem ] =-=-=-=-=-=-=-=-=-=-=
const mertypes = [ "a", "A" ];
/**
* Possible formats for the date
*/
export type meridiemType = "a" | "A";
export const isMeridiemType = (x: any): x is meridiemType => mertypes.includes(x);
// =-=-=-=-=-=-=-=-=-=-= [ Hours ] =-=-=-=-=-=-=-=-=-=-=
const hourtypes = [ "g", "G", "h", "H" ];
/**
* Possible formats for the date
*/
export type hourType = "g" | "G" | "h" | "H";
export const isHourType = (x: any): x is hourType => hourtypes.includes(x);
// =-=-=-=-=-=-=-=-=-=-= [ Minutes ] =-=-=-=-=-=-=-=-=-=-=
const minutetypes = [ "i" ];
/**
* Possible formats for the date
*/
export type minuteType = "i";
export const isMinuteType = (x: any): x is minuteType => minutetypes.includes(x);
// =-=-=-=-=-=-=-=-=-=-= [ Seconds ] =-=-=-=-=-=-=-=-=-=-=
const secondtypes = [ "s" ];
/**
* Possible formats for the date
*/
export type secondType = "s";
export const isSecondType = (x: any): x is secondType => secondtypes.includes(x);
// ############################## [ Date Formats ] ##############################
// =-=-=-=-=-=-=-=-=-=-= [ Date ] =-=-=-=-=-=-=-=-=-=-=
const dtypes = [ "j", "d", "D", "l", "w" ];
/**
* Possible formats for the date
*/
export type dateType = "j" | "d" | "D" | "l" | "w";
export const isDateType = (x: any): x is dateType => dtypes.includes(x);
// =-=-=-=-=-=-=-=-=-=-= [ Month ] =-=-=-=-=-=-=-=-=-=-=
const mtypes = [ "n", "m", "M", "F" ];
/**
* Possible formats for the month
*/
export type monthType = "n" | "m" | "M" | "F";
export const isMonthType = (x: any): x is monthType => mtypes.includes(x);
// =-=-=-=-=-=-=-=-=-=-= [ Year ] =-=-=-=-=-=-=-=-=-=-=
const yeartypes = [ "L", "o", "y", "Y" ];
/**
* Possible formats for the year
*/
export type yearType = "L" | "o" | "y" | "Y";
export const isYearType = (x: any): x is yearType => yeartypes.includes(x);

View File

@ -0,0 +1,14 @@
import TymeJS from "../index";
test(`Formatting Test`, () => {
let ts = new Date();
ts.setFullYear(1998);
ts.setMonth(9);
ts.setDate(24);
let ty = new TymeJS(ts);
expect(ty.format("d/m/Y")).toBe("24/10/1998")
})

View File

@ -1,12 +1,14 @@
import { dayDictionary } from "./Dictionaries/dateDictionary";
import { monthDictionary } from "./Dictionaries/monthDictionary"; import { monthDictionary } from "./Dictionaries/monthDictionary";
import { monthType } from "./Types/formatTypes"; import { commonDateFormats, dateType, hourType, isDateType, isHourType, isMeridiemType, isMinuteType, isMonthType, isSecondType, isYearType, meridiemType, minuteType, monthType, secondType, yearType } from "./Types/formatTypes";
/** /**
* The main Tyme Class, initialize it by optionally passing a date object * The main Tyme Class, initialize it by optionally passing a date object
* Created by Kato Twofold https://justkato.me
* @author Kato Twofold
* @example new TymeJS().format("d/m/Y h:i A")
* @class
*/ */
export default class TymeJS { export default class TymeJS {
@ -30,42 +32,184 @@ export default class TymeJS {
* Get the currently assigned date object * Get the currently assigned date object
* @returns The assigned Date object * @returns The assigned Date object
*/ */
public getDate(): Date { public getDateObject(): Date {
return this.ts; return this.ts;
} }
/**
* @returns a string representation of a date. The format of the string depends on the locale.
*/
public toString(): string {
// Return the current date as a string
return this.getDateObject().toString();
}
/** /**
* Format the current timestamp to a workable format * Format the current timestamp to a workable format
* @param dateTimeFormat * @param dateTimeFormat
* @returns The date formatted in the provided dateTimeFormat * @returns The date formatted in the provided dateTimeFormat
*/ */
public format(dateTimeFormat: string): string { public format(dateTimeFormat: commonDateFormats | string ): string {
/** /**
* The formatted date * The formatted date
*/ */
let formattedDate = ``; let formattedDate = ``;
// Go through all of the characters of the dateTimeFormat string
for ( let char of Array.from(dateTimeFormat) ) {
// Check which one of the formatters can handle this
if ( isDateType(char) )
formattedDate += this.getDate(char);
else if ( isMonthType(char) )
formattedDate += this.getMonth(char);
else if ( isYearType(char) )
formattedDate += this.getYear(char);
else if ( isMeridiemType(char) )
formattedDate += this.getMeridiem(char);
else if ( isHourType(char) )
formattedDate += this.getHour(char);
else if ( isMinuteType(char) )
formattedDate += this.getMinutes(char);
else if ( isSecondType(char) )
formattedDate += this.getSeconds(char);
else {
// Just append the char to the result
formattedDate += char;
}
}
// Return the formatted date // Return the formatted date
return formattedDate; return formattedDate;
} }
/**
* Get the current month
*/
public getMonth(mType: monthType): string {
// ############################## [ Time Formats ] ##############################
public getMeridiem(t: meridiemType): string {
// Get the current meridiem
let meridiem = ((this.ts.getHours() + 11) % 12 + 1) > 12 ? "pm" : "am";
// Check which format to return
if ( t === "A" ) {
return meridiem.toUpperCase();
} else if ( t === "a" ) {
return meridiem;
}
throw new Error(`Invalid format for meridiem ${t}`);
}
public getHour(t: hourType): string | number {
// Get current hour
let h = this.ts.getHours();
if ( t == "G" ) {
return h;
} else if ( t === "g" ) {
if ( h > 12 )
return h - 12;
return h;
} else if ( t === "H" ) {
return String(h).padStart(2, "0");
} else if ( t === "h" ) {
if ( h > 12 )
return String(h - 12).padStart(2, "0");
return String(h).padStart(2, "0");
}
throw new Error(`Invalid format for Hours ${t}`);
}
public getMinutes(t: minuteType ): string {
if ( t === "i" ) {
return String(this.ts.getMinutes()).padStart(2, "0");
}
throw new Error(`Invalid format for Minutes ${t}`);
}
public getSeconds(t: secondType) {
if ( t === "s" ) {
return String(this.ts.getSeconds()).padStart(2, "0");
}
throw new Error(`Invalid format for Seconds ${t}`);
}
// ############################## [ Date Formats ] ##############################
/**
*
* @param t The format to get the date in
* @returns A string of the formatted date
*/
public getDate(t: dateType): string | number {
if ( t == "j" ) {
// get the index of the current day
let currentDate: number = this.ts.getDate();
return currentDate;
} else if ( t == "d" ) {
// get the index of the current day
let currentDate: number = this.ts.getDate();
return String(currentDate).padStart(2, "0");
} else if ( t == 'w' ) {
return String(this.ts.getDay());
} else if ( t == "l") {
return String(dayDictionary[this.ts.getDay()]);
} else if ( t == 'D' ) {
return String(dayDictionary[this.ts.getDay()]).slice(0, 3);
}
throw new Error(`Invalid format for date ${t}`);
}
/**
* Format the current date object's month
* @param t The format to get the date in
* @returns A string of the formatted date
*/
public getMonth(t: monthType): string | number {
// get the index of the current month
let monthIndex: number = this.ts.getMonth(); let monthIndex: number = this.ts.getMonth();
if ( mType === "single" ) { if ( t === "n" ) {
return String(monthIndex + 1); return (monthIndex + 1);
} else if ( mType === "double" ) { } else if ( t === "m" ) {
return String(monthIndex + 1).padStart(2, "0"); return String(monthIndex + 1).padStart(2, "0");
} else if ( mType === "short" ) { } else if ( t === "M" ) {
return monthDictionary[monthIndex].slice(0, 3); return monthDictionary[monthIndex].slice(0, 3);
} else { } else if ( t === "F" ) {
return monthDictionary[monthIndex]; return monthDictionary[monthIndex];
} }
throw new Error(`Invalid format for date ${t}`);
}
/**
* Format the current date object's year
* @param t The format to get the date in
* @returns A string of the formatted date
*/
public getYear(t: yearType): string | number {
if ( t == "L" ) {
return (TymeJS.isLeapYear(this.ts.getFullYear())) ? 1 : 0;
} else if ( t == 'Y' ) {
return this.ts.getFullYear();
} else if ( t == 'y' ) {
return String(this.ts.getFullYear()).slice(2);
} else if ( t == 'o' ) {
throw new Error(`Not yet implemented`);
}
throw new Error(`Invalid format for year ${t}`);
}
public static isLeapYear(year: number): boolean {
return new Date(year, 1, 29).getDate() === 29;
} }
} }

18
src/tests/dateTest.ts Normal file
View File

@ -0,0 +1,18 @@
import TymeJS from "..";
let d: Date = new Date();
for ( let i = 0; i < 7; i++ ) {
const a = new TymeJS(d);
console.log(d, {
single: a.getDate("j"),
double: a.getDate("d"),
dowdouble: a.getDate("w"),
full: a.getDate("l"),
short: a.getDate("D"),
});
d.setDate(d.getDate() + 1);
}

21
src/tests/fullTest.ts Normal file
View File

@ -0,0 +1,21 @@
import TymeJS from "../index";
const a = new TymeJS();
console.log("🌍", a.format("m/d/Y"));
console.log(a.format("d/m/Y"));
console.log(a.format("d/m/Y h:i A"));
console.log(a.format("d/m/Y H:i:s"));
console.log("\n🇺🇸\n", a.format("m/d/Y"));
console.log(a.format("m/d/Y"));
console.log(a.format("m/d/Y h:i A"));
console.log(a.format("m/d/Y H:i:s"));
console.log("\n🖥\n", a.format("m/d/Y"));
console.log(a.format("Y-m-d"));
console.log(a.format("Y-m-d H:i:s"));
console.log(`\n`);

View File

@ -1,4 +1,4 @@
import TymeJS from "../src"; import TymeJS from "..";
for ( let i = 0; i < 12; i++ ) { for ( let i = 0; i < 12; i++ ) {
@ -8,10 +8,10 @@ for ( let i = 0; i < 12; i++ ) {
const a = new TymeJS(currentMonth); const a = new TymeJS(currentMonth);
console.log({ console.log({
single: a.getMonth("single"), single: a.getMonth("n"),
double: a.getMonth("double"), double: a.getMonth("m"),
full: a.getMonth("full"), full: a.getMonth("F"),
short: a.getMonth("short"), short: a.getMonth("M"),
}); });
} }

View File

@ -42,12 +42,12 @@
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */ /* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist/", /* Specify an output folder for all emitted files. */ "outDir": "./lib", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */ // "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */ // "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
@ -97,5 +97,7 @@
/* Completeness */ /* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */
} },
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
} }