PHP's date_parse in TypeScript

How to use

Install via yarn add locutus and import: import { date_parse } from 'locutus/php/datetime/date_parse'.

Or with CommonJS: const { date_parse } = require('locutus/php/datetime/date_parse')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1date_parse('2006-12-12 10:00:00'){year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0, is_localtime: false}

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's date_parse looks like.

import { strtotime } from '../datetime/strtotime.ts'

type DateParseResult = {
year: number
month: number
day: number
hour: number
minute: number
second: number
fraction: number
is_localtime: boolean
}

export function date_parse(date: string): DateParseResult | false {
// discuss at: https://locutus.io/php/date_parse/
// original by: Brett Zamir (https://brett-zamir.me)
// example 1: date_parse('2006-12-12 10:00:00')
// returns 1: {year : 2006, month: 12, day: 12, hour: 10, minute: 0, second: 0, fraction: 0, is_localtime: false}

let ts: number | false

try {
ts = strtotime(date, undefined)
} catch (_e) {
ts = false
}

if (!ts) {
return false
}

const dt = new Date(ts * 1000)

const retObj: DateParseResult = {
year: dt.getFullYear(),
month: dt.getMonth() + 1,
day: dt.getDate(),
hour: dt.getHours(),
minute: dt.getMinutes(),
second: dt.getSeconds(),
fraction: Number.parseFloat(`0.${dt.getMilliseconds()}`),
is_localtime: dt.getTimezoneOffset() !== 0,
}

return retObj
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP datetime functions


Star