//import en from "javascript-time-ago/locale/en"; import moment from "moment-timezone"; import { dlog } from "./dlog"; export namespace dtime { export function getCurrentDate() { return new Date().toISOString(); } export function getDataFromString(str: string) { new Date(str); } export function getFormattedDate(str: string) { try { let d = new Date(str); return d.toLocaleString(); } catch (e) { return "Invalid"; } } // as both are ios - just check the substring export function isSameDay(day1: string, day2: string) { return day1.substring(0, 10) == day2.substring(0, 10); } export function fromNow(str: string) { return moment(str).fromNow(); } export function addDay(offset: any, error = "Invalid date"): Date { let date = new Date(new Date().getTime() + parseInt(offset) * 24 * 60 * 60 * 1000); if (date.toString() == "Invalid Date") { throw new Error(error); } return date; } export function throwIfPastDate(date: Date, error = "You provided a past data") { if (new Date().getTime() > date.getTime()) { throw new Error(error); } } export function getDateOnlyFromISO(str: string): string { try { let d = new Date(str); return d.toLocaleDateString(); } catch (e) { return "Unknown Date"; } } export function getTimeOnlyFromISO(str: string): string { try { let d = new Date(str); return d.toLocaleTimeString(); } catch (e) { return "Unknown Time"; } } const intervals = [ { label: "year", seconds: 31536000 }, { label: "month", seconds: 2592000 }, { label: "day", seconds: 86400 }, { label: "hour", seconds: 3600 }, { label: "minute", seconds: 60 }, { label: "second", seconds: 1 }, ]; export function getAgoString(dateISOString: string) { try { let date = new Date(dateISOString); const seconds = Math.floor((Date.now() - date.getTime()) / 1000); const interval = intervals.find((i) => i.seconds < seconds); const count = Math.floor(seconds / interval!!.seconds); return `${count} ${interval!!.label}${count !== 1 ? "s" : ""} ago`; } catch (e) { dlog.ex(e as Error); return ""; } } // this must return a number in second export function getEpocFromTime(iso: string): number { return parseInt(new Date(iso).getTime() / 1000 + ""); } export function getIstDateTime(iso: string): string { let tm = moment(iso).tz("Asia/Kolkata"); return tm.format("YYYY-MM-DD HH:mm:ss"); } export function getIstDate(iso: string): string { let tm = moment(iso).tz("Asia/Kolkata"); return tm.format("YYYY-MM-DD"); } export function getIstTime(iso: string): string { let tm = moment(iso).tz("Asia/Kolkata"); return tm.format("HH:mm:ss"); } } // test