Skip to content

Commit

Permalink
feat: 🎸 Support utcOffset as a string (HH:mm | HHmm)
Browse files Browse the repository at this point in the history
Provide support string support to utcOffset method. Valid string values
formats for utcOffset method are +HH:mm, -HH:mm, +HHmm and -HHmm.

✅ Closes: iamkun#1085
  • Loading branch information
Ognjen Jevremovic committed Mar 1, 2021
1 parent cb4f746 commit 03f0436
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/constant.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ export const INVALID_DATE_STRING = 'Invalid Date'
// regex
export const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/
export const REGEX_FORMAT = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g
export const REGEX_VALID_OFFSET_FORMAT = /[+-]\d\d(?::?\d\d)?/g
export const REGEX_OFFSET_HOURS_MINUTES_FORMAT = /([+-]|\d\d)/g
27 changes: 26 additions & 1 deletion src/plugin/utc/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
import { MILLISECONDS_A_MINUTE, MIN } from '../../constant'
import { MILLISECONDS_A_MINUTE, MIN, REGEX_VALID_OFFSET_FORMAT, REGEX_OFFSET_HOURS_MINUTES_FORMAT } from '../../constant'


function offsetFromString(value = '') {
const offset = value.match(REGEX_VALID_OFFSET_FORMAT)

if (!offset) {
return null
}

const [indicator, hoursOffset, minutesOffset] = `${offset[0]}`.match(REGEX_OFFSET_HOURS_MINUTES_FORMAT) || ['-', 0, 0]
const totalOffsetInMinutes = (+hoursOffset * 60) + (+minutesOffset)

if (totalOffsetInMinutes === 0) {
return 0
}

return indicator === '+' ? totalOffsetInMinutes : -totalOffsetInMinutes
}


export default (option, Dayjs, dayjs) => {
const proto = Dayjs.prototype
Expand Down Expand Up @@ -59,6 +78,12 @@ export default (option, Dayjs, dayjs) => {
}
return oldUtcOffset.call(this)
}
if (typeof input === 'string') {
input = offsetFromString(input)
if (input === null) {
return this
}
}
const offset = Math.abs(input) <= 16 ? input * 60 : input
let ins = this
if (keepLocalTime) {
Expand Down

0 comments on commit 03f0436

Please sign in to comment.