Skip to content

Commit

Permalink
v0.0.2
Browse files Browse the repository at this point in the history
  • Loading branch information
SylarLong committed Oct 30, 2023
1 parent 446ed6f commit 3c16c73
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lunar-lite",
"version": "0.0.1",
"version": "0.0.2",
"description": "精简版的农历和阳历日期转换库。",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
18 changes: 17 additions & 1 deletion src/__tests__/convertor.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { lunar2solar, solar2lunar } from "..";
import { lunar2solar, normalizeDateStr, solar2lunar } from "..";

describe("calendar/convertor", () => {
test("solar2lunar()", () => {
Expand Down Expand Up @@ -133,4 +133,20 @@ describe("calendar/convertor", () => {
expect((err as Error).message).toBe("invalid date.");
}
});

test("normalizeDateStr()", () => {
const data = {
"2023-12-1": [2023, 12, 1],
"1998-01-02": [1998, 1, 2],
"1987-1-08": [1987, 1, 8],
"2016-08-18": [2016, 8, 18],
"1986-7-15 12:23:59": [1986, 7, 15, 12, 23, 59],
"1986.7/15 12:23:59": [1986, 7, 15, 12, 23, 59],
"1986.07-15 12:23": [1986, 7, 15, 12, 23],
};

Object.entries(data).forEach(([key, value]) => {
expect(normalizeDateStr(key)).toStrictEqual(value);
});
});
});
22 changes: 14 additions & 8 deletions src/convertor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getLeapDays, getLeapMonth } from "./leap";
import { lunarDateToStr } from "./misc";

/**
* 将日期字符串 YYYY-MM-DD 或者一个 Date 对象分割为 [YYYY, M - 1, D]
* 将日期字符串 YYYY-MM-DD 或者一个 Date 对象分割为 [YYYY, M, D, H, m, s]
* 当参数为字符串时分割符可以是 `-` `.` 或者 `/`
*
* @param dateStr 日期字符串或者 Date 对象
Expand All @@ -14,15 +14,21 @@ import { lunarDateToStr } from "./misc";
*/
export const normalizeDateStr = (date: string | Date) => {
if (date instanceof Date) {
return [date.getFullYear(), date.getMonth() + 1, date.getDate()];
return [
date.getFullYear(),
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
}

const result = date
.split(/[. -/]/)
.filter((word) => word !== "")
.map((word) => +word.trim());

return result;
return date
.split(/[ ]+/)
.map((item) => item.split(/[-:/.]/))
.reduce((prev, next) => prev.concat(next), [])
.map((item) => +item);
};

/**
Expand Down

0 comments on commit 3c16c73

Please sign in to comment.