Skip to content

Instantly share code, notes, and snippets.

@cherepanov
Last active May 26, 2021 11:43
Show Gist options
  • Save cherepanov/6552a4873ae4d144955cc49f43a010ca to your computer and use it in GitHub Desktop.
Save cherepanov/6552a4873ae4d144955cc49f43a010ca to your computer and use it in GitHub Desktop.
dayjs mobx-state-tree types
import dayjs from 'dayjs';
import { types } from 'mobx-state-tree';
export const DateTimeType = types.custom<string | dayjs.Dayjs, dayjs.Dayjs>({
name: 'DateTime',
isTargetType(value) {
return dayjs.isDuration(value);
},
getValidationMessage(value) {
if (dayjs(value).isValid()) return '';
return `${value} + ' is not a Date`;
},
fromSnapshot(value) {
if (!value) {
return null;
}
if (dayjs.isDayjs(value)) {
return value;
}
return dayjs(value);
},
toSnapshot(value) {
if (dayjs.isDayjs(value)) {
return value.toISOString();
}
return value;
}
});
import dayjs from 'dayjs';
import { Duration } from 'dayjs/plugin/duration';
import { types } from 'mobx-state-tree';
/*
const DATE_FORMAT = "YYYY-MM-DD HH:mm:ss";
export const DateTime = types.custom({
fromSnapshot: string => moment.utc(string, DATE_FORMAT).local(),
toSnapshot: (mDate: moment.Moment) => mDate.format(DATE_FORMAT),
});
* */
export const DurationType = types.custom<Duration, Duration>({
name: 'Duration',
isTargetType(value) {
// value = dayjs.isDuration(value) ? value : dayjs.duration(value);
return dayjs.isDuration(value);
},
getValidationMessage(value: Duration) {
if (dayjs.isDuration(value)) return '';
return `${value} is not a Duration`;
},
fromSnapshot(value) {
debugger;
if (dayjs.isDuration(value)) {
return value;
}
return dayjs.duration(value);
},
toSnapshot(value: any) {
value = value === 'P0D' ? 0 : value;
// debugger;
if (dayjs.isDuration(value)) {
return value;
}
return dayjs.duration(value);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment