In Deno date and time can be handled through the built-in Javascript Date object. Deno also provides the standard datetime library which makes it very easy to get date & time in various formats.
Getting Date & Time Without Using External Library
The standard Javascript Date object can be used to get date & time. This is built-in to Deno and requires no import of external libraries.
// new Date object
let date_ob = new Date();
Date object has several methods to get date & time values.
- getDate() : returns numeric day of the month (1-31)
- getMonth() : returns numeric month (0-11)
- getFullYear() : returns 4-digit year
- getHours() : returns numeric hour, 24 hour format (0-23)
- getMinutes() : returns numeric minute (0-59)
- getSeconds() : returns numeric seconds (0-59)
Using these methods, date-time string of the required format (for example YYYY-MM-DD hh:mm:ss etc) can be created.
let date_ob = new Date();
// current date as DD
let date = ("0" + date_ob.getDate()).slice(-2);
// current month as MM
let month = ("0" + (date_ob.getMonth() + 1)).slice(-2);
// current year as YYYY
let year = date_ob.getFullYear();
// current hours as hh
let hours = date_ob.getHours();
// current minutes as mm
let minutes = date_ob.getMinutes();
// current seconds as ss
let seconds = date_ob.getSeconds();
// current date in YYYY-MM-DD format
console.log(year + "-" + month + "-" + date);
// current date & time in YYYY-MM-DD hh:mm:ss format
console.log(year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds);
// current time in hh:mm format
console.log(hours + ":" + minutes);
Getting Date & Time Using datetime Library
Deno provides the standard datetime library which contains helper functions dealing in date & time. Standard libraries are reviewed by Deno, so they can be used without hesitation.
The format() method of the library can be used to format date & time as per requirement.
import { format } from "https://deno.land/std@0.91.0/datetime/mod.ts";
// current date in YYYY-MM-DD format
console.log(format(new Date(), "yyyy-MM-dd"));
// current date & time in YYYY-MM-DD hh:mm:ss format
console.log(format(new Date(), "yyyy-MM-dd HH:mm:ss"));
// current time in hh:mm format
console.log(format(new Date(), "HH:mm"));
The following symbols are allowed in the format() method while creating a date-time string.
- yyyy : 4-digit year
- yy : 2-digit year
- M : numeric month (1-12)
- MM : 2-digit numeric month (01-12)
- d : numeric day (1-31)
- dd : 2-digit numeric day (01-31)
- H : numeric hour, 24 hour format (0-23)
- HH : 2-digit numeric hour, 24 hour format (00-23)
- h : numeric hour, 12 hour format (0-11)
- hh : 2-digit numeric hour, 12 hour format (00-11)
- m : numeric minute (0-59)
- mm : 2-digit numeric minute (00-59)
- s : numeric second (0-59)
- ss : 2-digit numeric second (00-59)
- a : AM or PM