Convert Timestamp to Readable Date
Build a script to convert Unix timestamp (in both seconds and milliseconds) to human-readable date.
Getting Started
Step 1
Download day.min.js
(opens in a new tab) and put the file in packages
folder.
Step 2
Create a script file in the script folder with the following code.
convert-timestamp.js
/*
@okjson.schemaVersion 1
@okjson.name Convert Timestamp
@okjson.description Convert Unix timestamp to human-readable date.
@okjson.icon clock
@okjson.preprocessInput no
@okjson.openResultInNewWindow no
@okjson.author OK JSON
@okjson.authorURL https://okjson.app
*/
$include('dayjs.min');
function main(timestamp) {
const number = parseFloat(timestamp);
if (isNaN(number)) {
$alert.error(
'Input Error',
`“${timestamp}” cannot be converted to number.`
);
return '';
}
let dayjsObject = null;
if (timestamp.length === 10) {
dayjsObject = dayjs.unix(number);
} else if (timestamp.length === 13) {
dayjsObject = dayjs(number);
} else {
$alert.error('Input Error', `“${timestamp}” is not a valid timestamp.`);
return '';
}
const formatted = dayjsObject.format('YYYY-MM-DD HH:mm:ss');
$alert.success(`Timestamp: ${timestamp}`, formatted);
return '';
}
Example Timestamp for Testing
Monday, May 1, 2023 12:00:00 AM (GMT)
1682899200