Below are some very important functions that you will need while working with timestamp or date in JavaScript.
// returns current timestamp
const set_current_timestamp = function() {
returnmoment().format(‘X’);
};
// converts timestamp to date
// pass timestamp in function
const getDateFormatFromTimeStamp = function(dt) {
returnmoment.unix(dt).format(‘MM/DD/YYYY’);
};
// returns timestamp of start of today
const getCurrentDateDayStartTimestamp = function() {
returnmoment(’00:00:00′, ‘HH:mm:ss’).format(‘X’);
};
// returns timestamp of end of today
const getCurrentDateDayEndTimestamp = function() {
returnmoment(’23:59:59′, ‘HH:mm:ss’).format(‘X’);
};
// converts date format to timestamp
// pass date in function Ex: 23-08-2019 10:23:10
const setDateFormatToTimeStamp = function(dt) {
returnmoment(dt, ‘DD-MM-YYYY h:mm:ss’).unix();
};
// converts time to timestamp for today
// pass time in function Ex: “10:25 am”
const getTimestampFromTime = function(time) {
returnmoment(time, ‘HH:mm A’).format(‘X’);
};
// returns start timestamp of current month
const getStartofMonth = () => {
returnmoment()
.startOf(‘month’)
.format(‘X’);
};
// returns end timestamp of current month
const getEndofMonth = () => {
returnmoment()
.endOf(‘month’)
.format(‘X’);
};
// returns start timestamp of any month of any year
// pass year and month in function Ex: 2019, april
const getMonthStartTimestamp = (year, month) => {
returnmoment()
.year(year)
.month(month)
.date(1)
.hours(0)
.minutes(0)
.seconds(0)
.milliseconds(0)
.format(‘X’);
};
// this function returns last of any month of any year
// this will work afor leap year also
// pass month and year in function argument Ex: (‘february’, 2024)
const getLastDayofMonth = (month, year) => {
returnmoment()
.month(month)
.year(year)
.daysInMonth();
};
// returns end timestamp of any month of any year
// to get end of month timestamp, last date of the month is also required
// Whatever the “getLastDateOfMonth” function returns is passed in this function’s argument
// pass year and month in function Ex: 2019, april,
const getMonthEndTimestamp = (year, month, lastDay) => {
returnmoment()
.year(year)
.month(month)
.date(lastDay)
.hours(23)
.minutes(59)
.seconds(59)
.milliseconds(0)
.format(‘X’);
};
// returns timestamp from time format of any day
// pass timestamp in function
const convertTimestampToTime = timestamp => {
returnmoment(timestamp*1000).format(‘hh:mm a’);
};
// returns start timesamp of any day
// pass date in YYYY-MM-DD format to the function Ex: 2019-04-02
const getDateStartTimtstamp = date => {
returnmoment(date)
.startOf(‘day’)
.format(‘X’);
};
// returns end timesamp of any day
// pass date in YYYY-MM-DD format to the function Ex: 2019-04-02
const getDateEndTimtstamp = date => {
returnmoment(date)
.endOf(‘day’)
.format(‘X’);
};