Compare commits

..

No commits in common. "master" and "9429bfa374cac4063b6e3c506f52f614e27e6205" have entirely different histories.

18 changed files with 32 additions and 7615 deletions

4
.gitignore vendored
View File

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

View File

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

View File

View File

@ -1,90 +1 @@
![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
# Tyme.js

0
dist/.keep vendored
View File

View File

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

21
license
View File

@ -1,21 +0,0 @@
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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

7164
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,36 +1,18 @@
{
"name": "tymejs",
"version": "0.4.5",
"version": "0.1.0",
"description": "Quickly and easily format JavaScript date Objects",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"buildweb": "esbuild src/index.ts --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 --outfile=dist/tyme.js",
"test": "jest --config jestconfig.json"
"build": "esbuild src/index.ts --bundle --minify --sourcemap --target=chrome58,firefox57,safari11,edge16 --outfile=dist/tyme.js",
"test": "tsc"
},
"keywords": [
"time",
"time format",
"date",
"date format",
"datetime",
"datetime format",
"date",
"format"
],
"author": "Kato Twofold",
"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/**/*"
]
"license": "MIT"
}

View File

@ -1,17 +0,0 @@
/**
* 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,67 +1 @@
// 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);
export type monthType = "single" | "double" | "short" | "full"

View File

@ -1,14 +0,0 @@
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,14 +1,12 @@
import { dayDictionary } from "./Dictionaries/dateDictionary";
import { monthDictionary } from "./Dictionaries/monthDictionary";
import { commonDateFormats, dateType, hourType, isDateType, isHourType, isMeridiemType, isMinuteType, isMonthType, isSecondType, isYearType, meridiemType, minuteType, monthType, secondType, yearType } from "./Types/formatTypes";
import { monthDictionary } from "./Dictionaries/monthDictionary";
import { monthType } from "./Types/formatTypes";
/**
* 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 {
@ -32,184 +30,42 @@ export default class TymeJS {
* Get the currently assigned date object
* @returns The assigned Date object
*/
public getDateObject(): Date {
public getDate(): Date {
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
* @param dateTimeFormat
* @returns The date formatted in the provided dateTimeFormat
*/
public format(dateTimeFormat: commonDateFormats | string ): string {
public format(dateTimeFormat: string): string {
/**
* The formatted date
*/
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 formattedDate;
}
// ############################## [ 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
* Get the current month
*/
public getDate(t: dateType): string | number {
public getMonth(mType: monthType): string {
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();
if ( t === "n" ) {
return (monthIndex + 1);
} else if ( t === "m" ) {
if ( mType === "single" ) {
return String(monthIndex + 1);
} else if ( mType === "double" ) {
return String(monthIndex + 1).padStart(2, "0");
} else if ( t === "M" ) {
} else if ( mType === "short" ) {
return monthDictionary[monthIndex].slice(0, 3);
} else if ( t === "F" ) {
} else {
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;
}
}

View File

@ -1,18 +0,0 @@
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);
}

View File

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

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`. */
/* 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. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not 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. */
"outDir": "./lib", /* Specify an output folder for all emitted files. */
"outDir": "./dist/", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "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. */
@ -97,7 +97,5 @@
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
}