Skip to content

Commit

Permalink
fix: Fix objectSupport plugin bug in UTC (#1107)
Browse files Browse the repository at this point in the history
fix #1105
  • Loading branch information
iamkun authored Oct 5, 2020
1 parent 7937ccd commit fe90bb6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
10 changes: 5 additions & 5 deletions src/plugin/objectSupport/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export default (o, c) => {
export default (o, c, dayjs) => {
const proto = c.prototype
const isObject = obj => !(obj instanceof Date) && !(obj instanceof Array) && obj instanceof Object
const prettyUnit = (u) => {
Expand All @@ -9,13 +9,13 @@ export default (o, c) => {
const { date, utc } = cfg
const $d = {}
if (isObject(date)) {
const now = new Date()
const now = utc ? dayjs.utc() : dayjs()
Object.keys(date).forEach((k) => {
$d[prettyUnit(k)] = date[k]
})
const d = $d.day || ((!$d.year && !($d.month >= 0)) ? now.getDate() : 1)
const y = $d.year || now.getFullYear()
const M = $d.month >= 0 ? $d.month : ((!$d.year && !$d.day) ? now.getMonth() : 0)// eslint-disable-line no-nested-ternary,max-len
const d = $d.day || ((!$d.year && !($d.month >= 0)) ? now.date() : 1)
const y = $d.year || now.year()
const M = $d.month >= 0 ? $d.month : ((!$d.year && !$d.day) ? now.month() : 0)// eslint-disable-line no-nested-ternary,max-len
const h = $d.hour || 0
const m = $d.minute || 0
const s = $d.second || 0
Expand Down
11 changes: 8 additions & 3 deletions test/plugin/objectSupport.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ const now = new Date()
const currentYear = now.getFullYear()
const currentMonth = utils.s(now.getMonth() + 1, 2, '0')
const currentDate = utils.s(now.getDate(), 2, '0')
const currentUTCYear = now.getUTCFullYear()
const currentUTCMonth = utils.s(now.getUTCMonth() + 1, 2, '0')
const currentUTCDate = utils.s(now.getUTCDate(), 2, '0')
const fmt = 'YYYY-MM-DD HH:mm:ss.SSS'
const tests = [
[{ year: 2010 }, '2010-01-01 00:00:00.000'],
Expand All @@ -31,7 +34,8 @@ const tests = [
{
hour: 15, minute: 25, second: 50, millisecond: 125
},
`${currentYear}-${currentMonth}-${currentDate} 15:25:50.125`],
`${currentYear}-${currentMonth}-${currentDate} 15:25:50.125`,
`${currentUTCYear}-${currentUTCMonth}-${currentUTCDate} 15:25:50.125`],
[
{
year: 2010, month: 1, day: 12, hours: 1
Expand Down Expand Up @@ -119,8 +123,9 @@ it('Constructor from Object', () => {

it('Constructor from Object UTC', () => {
for (let i = 0; i < tests.length; i += 1) {
expect(dayjs.utc(tests[i][0]).format(fmt)).toBe(tests[i][1])
expect(moment.utc(tests[i][0]).format(fmt)).toBe(tests[i][1])
const result = tests[i][2] || tests[i][1]
expect(dayjs.utc(tests[i][0]).format(fmt)).toBe(result)
expect(moment.utc(tests[i][0]).format(fmt)).toBe(result)
}
})
it('Set from Object', () => {
Expand Down

0 comments on commit fe90bb6

Please sign in to comment.