Skip to content

Commit 06d0544

Browse files
committed
refactor: Refactor time layout parsing logic #296
1 parent 968ae0a commit 06d0544

1 file changed

Lines changed: 16 additions & 25 deletions

File tree

parser.go

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -54,38 +54,29 @@ func ParseByLayout(value, layout string, timezone ...string) *Carbon {
5454
if c.HasError() {
5555
return c
5656
}
57-
if layout == TimestampLayout {
58-
ts, err := parseTimestamp(value)
59-
if err != nil {
60-
c.Error = err
61-
return c
62-
}
63-
return CreateFromTimestamp(ts, c.Timezone())
64-
}
65-
if layout == TimestampMilliLayout {
66-
ts, err := parseTimestamp(value)
67-
if err != nil {
68-
c.Error = err
69-
return c
70-
}
71-
return CreateFromTimestampMilli(ts, c.Timezone())
72-
}
73-
if layout == TimestampMicroLayout {
57+
58+
// timestamp layouts
59+
switch layout {
60+
case TimestampLayout, TimestampMilliLayout, TimestampMicroLayout, TimestampNanoLayout:
7461
ts, err := parseTimestamp(value)
7562
if err != nil {
7663
c.Error = err
7764
return c
7865
}
79-
return CreateFromTimestampMicro(ts, c.Timezone())
80-
}
81-
if layout == TimestampNanoLayout {
82-
ts, err := parseTimestamp(value)
83-
if err != nil {
84-
c.Error = err
85-
return c
66+
67+
switch layout {
68+
case TimestampLayout:
69+
return CreateFromTimestamp(ts, c.Timezone())
70+
case TimestampMilliLayout:
71+
return CreateFromTimestampMilli(ts, c.Timezone())
72+
case TimestampMicroLayout:
73+
return CreateFromTimestampMicro(ts, c.Timezone())
74+
case TimestampNanoLayout:
75+
return CreateFromTimestampNano(ts, c.Timezone())
8676
}
87-
return CreateFromTimestampNano(ts, c.Timezone())
8877
}
78+
79+
// other layouts
8980
tt, err := time.ParseInLocation(layout, value, c.loc)
9081
if err != nil {
9182
c.Error = fmt.Errorf("%w: %w", ErrMismatchedLayout(value, layout), c.Error)

0 commit comments

Comments
 (0)