date-fns#format TypeScript Examples
The following examples show how to use
date-fns#format.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From vsinder-app with Apache License 2.0 | 7 votes |
export function dtToHumanStr(dt: Date) {
const ms = new Date().getTime() - dt.getTime();
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(ms / 60 / 1000);
const hours = Math.floor(ms / 60 / 60 / 1000);
if (hours > 140) {
return `${format(dt, "MMM d, yyyy")}`;
}
if (hours > 23) {
return `${format(dt, "EEEE")}`;
}
if (hours > 0) {
return `${hours}h`;
}
if (minutes > 0) {
return `${minutes}m`;
}
if (seconds > 0) {
return `${seconds}s`;
}
return "0s";
}
Example #2
Source File: utils.ts From vsinder with Apache License 2.0 | 7 votes |
export function dtToHumanStr(dt: Date) {
const ms = new Date().getTime() - dt.getTime();
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(ms / 60 / 1000);
const hours = Math.floor(ms / 60 / 60 / 1000);
if (hours > 140) {
return `${format(dt, "MMM d, yyyy")}`;
}
if (hours > 23) {
return `${format(dt, "EEEE")}`;
}
if (hours > 0) {
return `${hours}h`;
}
if (minutes > 0) {
return `${minutes}m`;
}
if (seconds > 0) {
return `${seconds}s`;
}
return "0s";
}
Example #3
Source File: dedupeTimestamp.ts From anchor-web-app with Apache License 2.0 | 6 votes |
export function dedupeTimestamp<Item extends {}>(
data: Item[],
timestampKey: keyof Item,
): Item[] {
const dedupedData: Item[] = [];
const indicies: Map<string, number> = new Map();
for (const item of data) {
//@ts-ignore
const timestamp: JSDateTime = item[timestampKey];
if (!timestamp) {
continue;
}
const dateString = format(timestamp, 'yyyyMMdd');
if (indicies.has(dateString)) {
dedupedData[indicies.get(dateString)!] = item;
} else {
const nextIndex = dedupedData.push(item) - 1;
indicies.set(dateString, nextIndex);
}
}
return dedupedData;
}
Example #4
Source File: filters.tsx From ke with MIT License | 6 votes |
DateTimeFilter = (params: DateTimeFilterProps): JSX.Element => {
const [currentDate, setCurrentDate] = React.useState<Date | null | undefined>()
const { name, label, resourceName, gotoPage, filterDate, filterTime } = params
const history = useHistory()
const location = useLocation()
const handleChange = (value: DatePickerValue): void => {
const singleValue = getDateFromDatePicker(value)
const filterValue = singleValue ? format(singleValue, "yyyy-MM-dd'T'HH:mm:ss") : ''
pushAnalytics({
eventName: EventNameEnum.DATETIME_CHANGE,
...getCommonFilterAnalyticsPayload(resourceName, filterValue, name),
...params,
})
setFilterValue(location, name, filterValue, history, gotoPage)
setCurrentDate(singleValue)
}
return (
<StyledFilter>
<DatePicker
className="styled-filter base-styled-filter"
onChange={(value) => handleChange(value)}
showTimeSelect
selected={currentDate}
dateFormat="yyyy-MM-dd HH:mm:ss"
placeholderText={`Фильтр по ${label}`}
filterDate={filterDate}
filterTime={filterTime}
/>
</StyledFilter>
)
}
Example #5
Source File: axisUtils.ts From anchor-web-app with Apache License 2.0 | 6 votes |
export function xTimestampAxis(datetimes: JSDateTime[]): string[] {
return datetimes.map((timestamp, i) => {
return i === datetimes.length - 1
? 'Now'
: checkTickPrint(i, datetimes.length, timestamp)
? format(timestamp, 'MMM')
: '';
});
}
Example #6
Source File: BasicCell.tsx From firetable with Apache License 2.0 | 6 votes |
export default function Date_({ value }: IBasicCellProps) {
if (!!value && "toDate" in value) {
try {
const formatted = format(value.toDate(), DATE_FORMAT);
return (
<>
<DateIcon style={{ marginRight: 5 }} />
{formatted}
</>
);
} catch (e) {
return null;
}
}
return null;
}
Example #7
Source File: filters.tsx From ke with MIT License | 6 votes |
DateFilter = (params: DateTimeFilterProps): JSX.Element => {
const [currentDate, setCurrentDate] = React.useState<Date | null | undefined>()
const { name, label, resourceName, gotoPage, filterDate, filterTime } = params
const history = useHistory()
const location = useLocation()
const handleChange = (value: DatePickerValue): void => {
const singleValue = getDateFromDatePicker(value)
const filterValue = singleValue ? format(singleValue, 'yyyy-MM-dd') : ''
pushAnalytics({
eventName: EventNameEnum.DATE_CHANGE,
...getCommonFilterAnalyticsPayload(resourceName, filterValue, name),
...params,
})
setFilterValue(location, name, filterValue, history, gotoPage)
setCurrentDate(singleValue)
}
return (
<StyledFilter>
<DatePicker
className="styled-filter base-styled-filter"
onChange={(value) => handleChange(value)}
selected={currentDate}
dateFormat="yyyy-MM-dd"
placeholderText={`Фильтр по ${label}`}
filterDate={filterDate}
filterTime={filterTime}
/>
</StyledFilter>
)
}
Example #8
Source File: OrderChart.tsx From ra-enterprise-demo with MIT License | 6 votes |
aggregateOrdersByDay = (orders: Order[]): { [key: string]: number } =>
orders
.filter((order: Order) => order.status !== 'cancelled')
.reduce((acc, curr) => {
const day = format(curr.date, 'YYYY-MM-DD');
if (!acc[day]) {
acc[day] = 0;
}
acc[day] += curr.total;
return acc;
}, {} as { [key: string]: number })
Example #9
Source File: types-mysql.test.ts From rds-data with MIT License | 6 votes |
test('Insert row of different data types', async () => {
const rds = setupRDSDatabase().getInstance();
let results = await rds.query(
`INSERT INTO ${TABLE} (id,bin,bit,ts,dte,dt,i,txt,ch,vc)
VALUES(null,UNHEX(:uid),1,NOW(),:dte,:dt,:i,:txt,:ch,:vc)`,
{ uid, ts: format(d, 'yyyy-MM-dd HH:mm:ss'), dte: format(d, 'yyyy-MM-dd HH:mm:ss'), dt: format(d, 'yyyy-MM-dd'), i, txt, ch, vc },
);
expect(results.insertId).not.toBe(0);
expect(results.numberOfRecordsUpdated).toBe(1);
const pk = results.insertId;
results = await rds.query(
`SELECT id,HEX(bin) AS b58,bit,ts,dte,dt,ui,i,txt,ch,vc
FROM ${TABLE}
WHERE id = :pk`,
{ pk },
);
expect(results.data.length).toBe(1);
expect(results.columns.length).toBe(11);
expect(results.insertId).toBe(0);
expect(results.numberOfRecordsUpdated).toBe(0);
const row = results.data[0];
expect(row.id.number).toBe(pk);
expect((row.b58.string || '').toLowerCase()).toBe(uid.toLowerCase());
expect(row.bit.boolean).toBe(true);
// TODO: what the hell is wrong with this?
// expect(row.ts.string).toBe(format(d, 'yyyy-MM-dd HH:mm:ss'));
expect(row.dte.string).toBe(format(d, 'yyyy-MM-dd HH:mm:ss'));
expect(row.dt.string).toBe(format(d, 'yyyy-MM-dd'));
expect(row.i.number).toBe(i);
expect(row.txt.string).toBe(txt);
expect(row.ch.string).toBe(ch);
expect(row.vc.string).toBe(vc);
});
Example #10
Source File: TableCell.tsx From firetable with Apache License 2.0 | 6 votes |
export default function User({ value }: IHeavyCellProps) {
if (!value || !value.displayName || !value.timestamp) return null;
const dateLabel = format(
value.timestamp.toDate ? value.timestamp.toDate() : value.timestamp,
DATE_TIME_FORMAT
);
return (
<Tooltip title={dateLabel}>
<Chip
avatar={<Avatar alt="Avatar" src={value.photoURL} />}
label={value.displayName}
/>
</Tooltip>
);
}
Example #11
Source File: date.tsx From livepeer-com with MIT License | 6 votes |
DateCell = <D extends TableData>({
cell,
}: CellComponentProps<D, DateCellProps>) => {
try {
return format(cell.value.date, "MMMM dd, yyyy h:mm a");
} catch (error) {
return cell.value.fallback;
}
}
Example #12
Source File: types-pg.test.ts From rds-data with MIT License | 6 votes |
test('Insert row of unique types', async () => {
const rds = setupRDSDatabase().getInstance();
let results = await rds.query(
`INSERT INTO ${TABLE} (bin,bool,ts,dte,dt,i,txt,ch,vc)
VALUES(decode(:uid, 'hex'),true,NOW(),:dte,:dt,:i,:txt,:ch,:vc)
RETURNING id`,
{ uid, dte: format(d, 'yyyy-MM-dd HH:mm:ss'), dt: format(d, 'yyyy-MM-dd'), i, txt, ch, vc },
);
// this is 0 if we have the RETURNING clause
expect(results.numberOfRecordsUpdated).toBe(0);
const pk = results.data[0].id.number!;
results = await rds.query(
`SELECT id,encode(bin, 'hex') AS b58,bool,ts,dte,dt,i,txt,ch,vc
FROM ${TABLE}
WHERE id = :pk`,
{ pk },
);
expect(results.data.length).toBe(1);
expect(results.columns.length).toBe(10);
expect(results.insertId).toBe(0);
expect(results.numberOfRecordsUpdated).toBe(0);
const row = results.data[0];
expect(row.id.number).toBe(pk);
expect(row.b58.string!.toLowerCase()).toBe(uid.toLowerCase());
expect(row.bool.boolean).toBe(true);
// TODO
// expect(row.ts.string).toBe(format(d, 'yyyy-MM-dd HH:mm:ss'));
expect(row.dte.string).toBe(format(d, 'yyyy-MM-dd HH:mm:ss'));
expect(row.dt.string).toBe(format(d, 'yyyy-MM-dd'));
expect(row.i.number).toBe(i);
expect(row.txt.string).toBe(txt);
expect(row.ch.string).toBe(ch);
expect(row.vc.string).toBe(vc);
});
Example #13
Source File: JoinedDate.tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export default function JoinedDate({
date,
...props
}: JoinedDateProps): ReactElement {
return (
<div {...props}>
Joined
<time dateTime={date.toISOString()}>{format(date, 'MMMM y')}</time>
</div>
);
}
Example #14
Source File: PostCard.tsx From Cromwell with MIT License | 6 votes |
PostInfo = (props: { data?: TPost }) => {
const { data } = props;
const avatar = data?.author?.avatar;
return (
<div className={styles.authorBlock}>
{(avatar && avatar !== '') ? (
<div className={styles.avatar} style={{ backgroundImage: `url(${avatar})` }}></div>
) : <AccountCircleIcon className={styles.avatar} />}
<div>
<p className={styles.authorName} >{data?.author?.fullName}</p>
<div className={styles.dateAndReadInfo}>
<p className={styles.publishDate}>{data?.publishDate ? format(Date.parse(String(data.publishDate)), 'd MMMM yyyy') : ''}</p>
{(data?.readTime && parseInt(data.readTime) !== 0) && (
<p className={styles.readTime}>{Math.round(parseFloat(data.readTime))} min read</p>
)}
</div>
</div>
</div>
)
}
Example #15
Source File: index.tsx From GoBarber with MIT License | 6 votes |
AppointmentCreated: React.FC = () => {
const { reset } = useNavigation();
const { params } = useRoute();
const { date } = params as RouteParams;
const formattedDate = useMemo(() => {
return format(date, "EEEE', dia' dd 'de' MMMM 'de' yyyy 'às' HH:mm'h'", {
locale: ptBR,
});
}, [date]);
const handleOkPressed = useCallback(() => {
reset({
routes: [
{
name: 'Dashboard',
},
],
index: 0,
});
}, [reset]);
return (
<Container>
<Icon name="check" size={80} color="#04d361" />
<Title>Agendamento Concluído</Title>
<Description>{formattedDate}</Description>
<OkButton onPress={handleOkPressed}>
<OkButtonText>Ok</OkButtonText>
</OkButton>
</Container>
);
}
Example #16
Source File: index.tsx From gobarber-mobile with MIT License | 6 votes |
AppointmentCreated: React.FC = () => {
const { reset } = useNavigation();
const { params } = useRoute();
const { date } = params as RouteParams;
const handleOkPressed = useCallback(() => {
reset({
routes: [{ name: 'Dashboard' }],
index: 0,
});
}, [reset]);
const formattedDate = useMemo(() => {
return format(date, "EEEE', dia' dd 'de' MMMM 'de' yyyy 'às' HH:mm'h'", {
locale: ptBR,
});
}, [date]);
return (
<Container>
<Icon name="check" size={80} color="#04d461" />
<Title>Agendamento concluído</Title>
<Description>{formattedDate}</Description>
<OkButton onPress={handleOkPressed}>
<OkButtonText>Ok</OkButtonText>
</OkButton>
</Container>
);
}
Example #17
Source File: dateFormat.ts From apps with GNU Affero General Public License v3.0 | 6 votes |
getReadHistoryDateFormat = (currentDate: Date): string => {
const today = new Date();
if (isDateOnlyEqual(today, currentDate)) {
return 'Today';
}
if (isDateOnlyEqual(today, addDays(currentDate, 1))) {
return 'Yesterday';
}
const dayOfTheWeek = format(currentDate, 'EEE');
const dayOfTheMonth = currentDate.getDate();
const month = format(currentDate, 'MMM');
const currentYear = currentDate.getFullYear();
const year = currentYear === today.getFullYear() ? '' : ` ${currentYear}`;
return `${dayOfTheWeek}, ${dayOfTheMonth} ${month}${year}`;
}
Example #18
Source File: index.tsx From gobarber-project with MIT License | 6 votes |
AppointmentCreated: React.FC = () => {
const { reset } = useNavigation();
const { params } = useRoute();
const { date } = params as IRouteParams;
const handleOkPressed = useCallback(() => {
reset({
routes: [
{
name: 'Dashboard',
},
],
index: 0,
});
}, [reset]);
const formattedDate = useMemo(() => {
return format(date, "EEEE', dia' dd 'de' MMMM 'de' yyyy 'às' HH:mm'h'", {
locale: ptBR,
});
}, [date]);
return (
<Container>
<Icon name="check" size={80} color="#04d361" />
<Title>Agendamento concluído</Title>
<Description>{formattedDate}</Description>
<OkButton onPress={handleOkPressed}>
<OkButtonText>OK</OkButtonText>
</OkButton>
</Container>
);
}
Example #19
Source File: DateTimeRangeListWidget.tsx From ke with MIT License | 6 votes |
getInputPayload = (dateRanges: DateRange[]): ([string, string] | null)[] =>
dateRanges.map((dateRange_: DateRange) => {
const [dateFrom, dateTo] = dateRange_
if (dateFrom && dateTo) {
return [format(dateFrom, "yyyy-MM-dd'T'HH:mm:ss"), format(dateTo, "yyyy-MM-dd'T'HH:mm:ss")]
}
return null
})
Example #20
Source File: postList.tsx From jeffjadulco.com with MIT License | 6 votes |
function Post({ post }: { post: Frontmatter }) {
return (
<li className="py-5">
<Link href={`blog/${post.slug}`}>
<a className="flex flex-col px-8 py-5 -my-5 transition-colors ease-in-out -mx-7 group sm:flex-row sm:justify-between sm:items-end hover:bg-back-secondary focus:bg-back-secondary focus-visible:outline-accent focus:text-accent">
<div>
<h3 className="text-xl font-semibold group-hover:text-accent">
{post.title}
</h3>
<h4 className="font-medium text-fore-subtle">{post.description}</h4>
</div>
<div className="mt-2 text-sm sm:mt-0 sm:text-base text-accent sm:text-fore-subtle">
{format(parseISO(post.publishedAt), 'MMMM yyyy')}
</div>
</a>
</Link>
</li>
)
}
Example #21
Source File: case_list.tsx From j3pz-web with MIT License | 6 votes |
private getTime = (date: string) => {
if (!date) return '';
const now = new Date();
const updateTime = new Date(date);
if (isSameDay(now, updateTime)) {
return format(updateTime, 'HH:mm');
}
if (isSameYear(now, updateTime)) {
return format(updateTime, 'MM月dd日 HH:mm');
}
return format(updateTime, 'yyyy年MM月dd日 HH:mm');
};
Example #22
Source File: console.test.ts From ironfish with Mozilla Public License 2.0 | 6 votes |
describe('logPrefix', () => {
it('omits logPrefix if logPrefix is an empty string', () => {
const spy = jest.spyOn(loggers, 'info').mockImplementationOnce(() => {})
const reporter = new ConsoleReporter()
reporter.defaultMinimumLogLevel = LogLevel.Info
reporter.logPrefix = ''
reporter.log({
args: ['testlog'],
date: new Date(),
level: LogLevel.Info,
type: 'info',
tag: 'test',
})
expect(spy).toBeCalledWith('testlog')
spy.mockRestore()
})
it('formats logPrefix if set', () => {
const spy = jest.spyOn(loggers, 'info').mockImplementationOnce(() => {})
const date = new Date()
const reporter = new ConsoleReporter()
reporter.defaultMinimumLogLevel = LogLevel.Info
reporter.logPrefix = '[%time%] [%tag%] [%level%]'
reporter.log({
args: ['testlog'],
date: date,
level: LogLevel.Info,
type: 'info',
tag: 'testtag',
})
expect(spy).toBeCalledWith(`[${format(date, 'HH:mm:ss.SSS')}] [testtag] [info]`, 'testlog')
spy.mockRestore()
})
})
Example #23
Source File: Notification.tsx From frontend.ro with MIT License | 6 votes |
Notification = ({ notification, onMarkAsRead, }: Props) => ( <li className={` ${styles.notification} ${!notification.read ? styles['is--unread'] : ''} text-xs `} onClick={() => onMarkAsRead(notification._id)} > <Link href={notification.href ?? '#'}> <a className="d-flex no-underline"> <img width="32" height="32" alt={notification.from ? `${notification.from.username} avatar` : 'FrontEnd.ro'} src={notification.from ? notification.from.avatar : `${process.env.CLOUDFRONT_PUBLIC}/public/logo-square--S.jpg`} /> <div className="body"> <p className="m-0"> {notification.from !== undefined && ( <span className={styles.user}> {notification.from?.name ?? notification.from?.username ?? ''} </span> )} {notification.short_message} </p> <time className="text-silver" dateTime={format(notification.timestamp, 'yyyy-MM-dd')} > {timeAgo(new Date(notification.timestamp))} </time> </div> </a> </Link> </li> )
Example #24
Source File: ArticlePage.tsx From ts-redux-react-realworld-example-app with MIT License | 6 votes |
function ArticleAuthorInfo({
article: {
author: { username, image },
createdAt,
},
}: {
article: Article;
}) {
return (
<Fragment>
<Link to={`/profile/${username}`}>
<img src={image || undefined} />
</Link>
<div className='info'>
<Link className='author' to={`/profile/${username}`}>
{username}
</Link>
<span className='date'>{format(createdAt, 'PP')}</span>
</div>
</Fragment>
);
}
Example #25
Source File: CoachingCard.tsx From nyxo-website with MIT License | 6 votes |
CoachingCard: FC<Props> = ({ coaching }) => {
const { t } = useTranslation()
return (
<Card>
<H5>
{`${
coaching?.started && format(new Date(coaching?.started), "dd.MM.yyyy")
}`}
</H5>
<ID>{coaching?.id}</ID>
<Info></Info>
<div>
{t("COACHING.ACTIVE_WEEK")} {coaching?.activeWeek}
</div>
<InformationRow>
<Lessons>
<Icon
height="20px"
width="20px"
name="presentation"
stroke="currentColor"
/>
{coaching?.lessons?.length} {t("LESSONS")}
</Lessons>
<Weeks>
<Icon
height="20px"
width="20px"
name="presentation"
stroke="currentColor"
/>
{coaching?.weeks?.length} {t("WEEKS")}
</Weeks>
</InformationRow>
</Card>
)
}
Example #26
Source File: sleep.ts From nyxo-app with GNU General Public License v3.0 | 6 votes |
fetchPolar = createAsyncThunk<Response, Arguments>(
'polar/fetch',
async ({ startDate }, { dispatch, rejectWithValue }) => {
try {
const token = await getAccess('polar')
if (token) {
const response: PolarSleepObject = await fetch(
`https://www.polaraccesslink.com/v3/users/sleep/${format(
new Date(startDate),
'yyyy-MM-dd'
)}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token.accessToken}`
}
}
)
dispatch(addNights(formatPolarSample(response)))
}
} catch (error) {
rejectWithValue(undefined)
}
}
)
Example #27
Source File: CountdownLabel.tsx From UUI with MIT License | 6 votes |
CountdownLabel = UUIFunctionComponent({
name: 'CountdownLabel',
nodes: {
Root: 'label',
},
propTypes: CountdownLabelPropTypes,
}, (props: CountdownLabelFeatureProps, { nodes }) => {
const { Root } = nodes
const finalProps = {
frequency: props.frequency || 1000,
format: props.format || 'hh:mm:ss',
allowNegative: props.allowNegative || false,
}
const generateLabelText = useCallback(() => {
const diff = differenceInMilliseconds(props.until, new Date())
const duration = (!props.allowNegative && diff && diff < 0)
? new Date(0)
: addMilliseconds(addHours(new Date(0), 16), diff)
return format(duration, finalProps.format)
}, [finalProps.format, props.allowNegative, props.until])
const [text, setText] = useState(generateLabelText())
useInterval(() => {
setText(generateLabelText())
}, finalProps.frequency)
return (
<Root>{text}</Root>
)
})
Example #28
Source File: PureLanguageHelper.ts From legend-studio with Apache License 2.0 | 6 votes |
generateDefaultParameterValueForType = (
type: Type | undefined,
index: number,
): string | number | boolean => {
if (!type) {
return `param${index}`;
}
if (type instanceof Enumeration) {
return type.values.length !== 0
? `${type.path}.${type.values[0]?.name}`
: `param${index}`;
} else if (type instanceof PrimitiveType) {
switch (type.name) {
case PRIMITIVE_TYPE.BOOLEAN:
return true;
case PRIMITIVE_TYPE.FLOAT:
case PRIMITIVE_TYPE.DECIMAL:
return 0.0;
case PRIMITIVE_TYPE.NUMBER:
case PRIMITIVE_TYPE.INTEGER:
return 0;
case PRIMITIVE_TYPE.DATE:
case PRIMITIVE_TYPE.STRICTDATE:
return `%${format(new Date(), 'yyyy-MM-dd')}`;
case PRIMITIVE_TYPE.DATETIME:
return `%${format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
case PRIMITIVE_TYPE.STRICTTIME:
return `%00:00:00`;
case PRIMITIVE_TYPE.STRING:
return "''";
default:
return `param${index}`;
}
}
// Other non-primitive types, e.g. Class
return `param${index}`;
}
Example #29
Source File: time.ts From nyxo-app with GNU General Public License v3.0 | 6 votes |
getFormattedDateOrPlaceholder = (
value: string | null | undefined,
formatter: string
): string => {
if (value) {
return format(parseISO(value), formatter)
}
return '-'
}