discord.js if date.now() function - javascript

I'm trying to get the current date (day, hour, minute, second) and put it in an if() statement to compare it with the date entered. But how am I able to get the date and ask for it in code?
This is what I got so far:
bot.on("ready", () => {
var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
var time = today.getHours() + ":" + today.getMinutes();
var currentdate = date + time
var endDate = new Date('2021-01-21T14:00:00')
if (endDate = currentdate) {
console.log('The time has come..')
} else {
console.log('The time is coming soon..')
}
})

you can use 'moment.js' like this :
const moment = require("moment");
getDifferenceInYear(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "years");
}
getDifferenceInDay(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "days");
}
getDifferenceInHour(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "hour");
}
getDifferenceInSecond(date_1, date_2) {
return moment(date_1).diff(moment(date_2), "second");
}
isNowBetween(startDate, endDate) {
return moment(new Date()).isBetween(startDate, endDate);
}

you can following this code for comparing:
let inputDate = '2021-01-21T14:00:00'
let endDate = Math.round(new Date(inputDate ) / 1000);
let cuurentDate = Math.round(new Date() / 1000)
if (cuurentDate == endDate ) {
console.log('The time has come..')
}
else {
console.log('The time is coming soon..')
}

Related

remove timezone in my random date generator in javascript

This is my code. I make it random but the timezone is always in there and i dont know how to disappear the timezone, can someone help me with this I'am beginner in this thanks
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
);
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
If you call the formatDate function you have in your code, I believe that will get rid of the timezone information.
var startDate = new Date("1990-01-01"); //YYYY-MM-DD
var endDate = new Date("2022-01-01"); //YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
/* getMonth returns dates from 0, so add one */
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month < 10 ? '0' : ''}${ month }-${ day < 10 ? '0' : '' }${day}`
}
var getDateArray = function(start, end) {
return formatDate(new Date(
start.getTime() + Math.random() * (end.getTime(0) - start.getTime(0))
));
}
var dateArr = getDateArray(startDate, endDate);
console.log(dateArr);
All I did here was add a call to your formatDate function within the getDateArray function so that now the return of the getDateArray will no longer contain timezone information.
Create these 2 functions to change the date format.
function DateFormat(startDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}
function DateFormat(endDate)
{
const strYear = date("Y",strtotime(strDate));
const strMonth= date("n",strtotime(strDate));
const strDay= date("j",strtotime(strDate));
return "${strYear}$-${strMonth}-${strDay}";
}

How to check if date is today or yetsterday or return date? [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
How can i check if input date is Today, Yesterday or just return the date if it's noone of them?
I was trying to do the following:
const checkDate = (someDate) => {
const today = new Date();
let date = new Date(someDate);
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
return date.getTime() === today.getTime() ? "Oggi" : date.getTime() === today.setDay(-1) ? "Ieri" : "Il" + date;
}
console.log(checkDate("December 17, 1995 03:24:00"));
Where "Oggi" is Today and "Ieri" is Yesterday..
The easiest and most probably the right way is to use some library. Try day.js - small, but features rich (similar to Moment).
To install:
npm install dayjs
Or CDN:
<script src="https://unpkg.com/dayjs#1.8.21/dayjs.min.js"></script>
And you are ready to use all the set of features:
const someDate = new Date(); // plain old JS date
const now = dayjs(); // same (current date) but with day.js
// of course you can do: dayjs(someDate)
// yesterday: you check if someDate is current date - 1 day
const isYesterday = dayjs(someDate).isSame(dayjs().subtract(1, 'day'))
// today: just check if some date is equal to current date
const isToday = dayjs(someDate).isSame(dayjs()); // dayjs() return current date
// want to get back to plain old JS date
conat plainOldJsDate = dayjs('2019-01-25').toDate();
You can find more awesome features like parsing, manipulating, formatting, etc. in official docs.
isToday:
const isToday = (date) => {
const today = new Date()
return date.getDate() === today.getDate() &&
date.getMonth() === today.getMonth() &&
date.getFullYear() === today.getFullYear();
};
isYesterday:
const isYesterday = (date) => {
var yesterday= new Date();
yesterday; //# => today
date.setDate(date.getDate() - 1);
yesterday; //# => yesterday
return date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear();
}
The issue was that i missed to set mills and setDay was invalid, solved by using setDate(getDate() - 1) and by setting mills to 0
Here is the final solution
const checkDate = (someDate) => {
let today = new Date();
let date = new Date(someDate);
date = resetHours(date);
today = resetHours(today);
return date.getTime() === today.getTime() ? "Oggi" : date.getTime() === today.setDate(today.getDate() - 1) ? "Ieri" : "Il" + date;
}
const resetHours = (date) => {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
return date;
}
You need to get the current date with a Date() object, then compare.
The function receives strings in the form of mm/dd/yyyy.
function checkDate(date) {
// get today
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
var yyyy = today.getFullYear();
// parse into strings
today = mm + '/' + dd + '/' + yyyy;
yesterday = mm + '/' + (dd-1) + '/' + yyyy;
if (today == date) {
return 'today';
}
if (today == yesterday) {
return 'yesterday';
}
else {
return date;
}
}
var date = '01/04/2021';
console.log(checkDate(date));
Compare .toDateString to check if a Date() is the same day:
const checkDate = (someDate) => {
// Create 'today' Date object
const today = new Date();
// Create 'someDate' Date object
const date = new Date(someDate);
// is Today
if (date.toDateString() === today.toDateString()) {
return 'today';
}
// Alter date to yesterday
today.setDate(today.getDate() - 1);
// is Yesterday
if (date.toDateString() === today.toDateString()) {
return 'yesterday';
}
// Fallback
return 'fallback'
}
console.log(checkDate('1/4/2021')); // today
console.log(checkDate('1/3/2021')); // yesterday
console.log(checkDate('1/9/2021')); // fallback
const isSameDay = (a, b) => {
return a.getFullYear() === b.getFullYear() &&
a.getMonth() === b.getMonth() &&
a.getDate()=== b.getDate();
}
const checkDate = (date) => {
const today = new Date();
const yesterday = new Date(Date.now() - 86400000); // 24 * 60 * 60 * 1000
if (isSameDay(today, date)) {
return "Today";
} else if (isSameDay(yesterday, date)) {
return "Yesterday";
} else {
return date.toDateString();
}
}
console.log(checkDate(new Date())); // "Today"
console.log(checkDate(new Date(Date.now() - 86400000))); // "Yesterday"
console.log(checkDate(new Date(Date.now() - 86400000 * 3))); // "Fri Jan 01 2021"
Date documentation in MDN

Parse String Time to JS Date Obj

I am trying to convert a string of time such as "7:30am" to JavaScript Date Object like Sat Nov 18 2017 7:30:00 GMT-0500 (EST)
My approach:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
I got Invalid Date for both startDate, endDate.
Try here:
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts.shift());
date.setMinutes(parts.shift());
return date
}
var startTime = "7:30am";
var endTime = "9:30pm";
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
var test = dateObj(startTime)
console.log(startDate, endDate)
I would rather use a regular expression to extract the date elements and also add some error handling for the case the date format is not valid.
And do not forget also to handle 12am and 12pm. This needs extra handling in the code.
See below:
function dateObj(d) { // date parser ...
const rx = /(\d{1,2})\:(\d{1,2})\s*(am|pm)/g;
const parts = rx.exec(d);
if (parts === null) {
return "Not a valid date: " + d;
}
date = new Date();
const amPm = parts.pop().toLowerCase();
const hour = parseInt(parts[1]);
if (amPm === 'pm') {
if (hour !== 12) {
parts[1] = (parseInt(parts[1])) + 12;
}
} else if (amPm === 'am' && hour === 12) {
parts[1] = 0;
}
date.setHours(parts[1]);
date.setMinutes(parts[2]);
return date
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
console.log(startDate, endDate)
console.log(dateObj("7:30 pm"))
console.log(dateObj("7:30 am"))
console.log(dateObj("7:30am"))
console.log(dateObj("12:30pm"))
console.log(dateObj("12:30 am"))
This is working for me if you enter 9:30 pm instead of 9:30pm, the white space needs to be there for regex:
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') {
parts[0] = parts[0] + 12;
}
date.setHours(parts[0]);
date.setMinutes(parts[1]);
return date;
}
It just needs a space before am/pm :
d = t => new Date(new Date().toDateString() + t.replace(/(.*\d)/, " $1 "))
console.log(d("7:30").toString())
console.log(d("7:30am").toString())
console.log(d("9:30pm").toString())
This will create a new Date object that includes the current time.
But it is based on the timezone of where the code is run.
var timeRe = /(\d+):(\d+)([amp]*)/gi;
function timeParse(time) {
var today = new Date();
var match = time.split(timeRe);
console.log(time, match);
if (match) {
var hours = parseInt(match[1],10)+(match[3].toLowerCase()==='pm'?12:0)%24;
today.setHours(hours);
today.setMinutes(parseInt(match[2],10));
today.setSeconds(0);
}
return today;
}
var startTime = "7:30";
var endTime = "9:30pm";
var startDate = timeParse(startTime); // get date objects
var endDate = timeParse(endTime);
console.log(startDate, endDate)

convert '18/10/2016 10:31:22PM' format into '18/10/2016 22:31:22' time format in javascript

var now = new Date('18/10/2016 10:31:22PM');
var time = now.toLocaleTimeString();
alert(time);
this function give an output invalid date. I want to convert this "18/10/2016 22:31:22" format. give me an appropriate example as a solution.
this function should work for your date format
function convertDate(date_string){
var d = date_string.trim();
d = d.split(" ");
v = d[1].split(":")[0];
v = d[1].indexOf("PM")>-1 ? +v+12 : v;
d[1] = d[1].replace(d[1].split(":")[0],v);
d = d.join(" ").replace("PM","").replace("AM","");
return d;
}
console.log(convertDate("18/10/2016 10:31:22PM"));
console.log(convertDate("01/10/2016 09:31:22PM"));
console.log(convertDate("06/10/2016 2:31:22AM"));
console.log(convertDate("07/10/2016 7:31:22AM"));
Without using a library, you will need to extract all the date tokens and send them into a new date object in the correct order. From there, you can create your own date formatting function.
var DATE_FORMAT = /(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2})([AP]M)/;
var dateStr = '18/10/2016 10:31:22PM';
var now = parseDateString(dateStr, DATE_FORMAT, function(tokens) {
return [
parseInt(tokens[3], 10), // year
parseInt(tokens[2], 10) - 1, // month
parseInt(tokens[1], 10), // date
to24(parseInt(tokens[4], 10), tokens[7]), // hours, meridiem
parseInt(tokens[5], 10), // minutes
parseInt(tokens[6], 10), // seconds
0 // milliseconds
];
});
document.body.innerHTML = formateDate(now);
function parseDateString(dateStr, dateFormat, func) {
var tokens = dateStr.match(dateFormat);
var args = Array.prototype.concat.apply([null], func(tokens));
return new (Function.prototype.bind.apply(Date, args));
}
function formateDate(date, dateSeparator) {
return [
pad2(date.getDate()),
pad2(date.getMonth() + 1),
date.getFullYear()
].join(dateSeparator || '/') + ' ' + [
pad2(date.getHours()),
pad2(date.getMinutes()),
pad2(date.getSeconds())
].join(':');
}
function pad2(str) { return ('00' + str).substr(-2); }
function to24(hours, meridiem) {
switch (meridiem) {
case 'PM': if (hours < 12) return hours + 12;
case 'AM': if (hours === 12) return hours - 12;
default: return hours;
}
}
Of course, this can be done in moment with one line.
var dateStr = '18/10/2016 10:31:22PM';
var time = moment(dateStr, 'DD/MM/YYYY hh:mm:ssA').format('DD/MM/YYYY HH:mm:ss');
document.body.innerHTML = time;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>

Convert local time to UTC in JavaScript

i have this code for working with dates.
<script language="javascript" type="text/javascript">
$("#Reports_SignUpDateAfter_container").datepicker({
changeYear: true,
changeMonth: true,
dateFormat: 'dd-mm-yy', //"dd-mm-yy",
gotoCurrent: true,
yearRange: '-10:+10',
onSelect: function() {
Reports_SignUpDateAfter_changeDate(false);
}
});
// react on manual text box editing
$("#Reports_SignUpDateAfter_container").change(function() {
Reports_SignUpDateAfter_changeDate(true);
});
function Reports_SignUpDateAfter_changeDate(manualChange) {
var newDate = $("#Reports_SignUpDateAfter_container").datepicker("getDate");
if (newDate != null) {
// add time information
newDate = DateUtils.copyTimeFrom("#Reports_SignUpDateAfter_local", newDate);
DateUtils.setDate("#Reports_SignUpDateAfter_local", newDate);
// convert local to UTC
Reports_SignUpDateAfter_localToUTC();
if (manualChange) {
$("#Reports_SignUpDateAfter_container").datepicker("setDate", newDate)
}
} else { // empty
$("#Reports_SignUpDateAfter_local").val("");
$("#Reports_SignUpDateAfter").val("");
}
}
// new date as UTC
function Reports_SignUpDateAfter_setDate(newDate) {
// store time into hidden inputs
DateUtils.setDate("#Reports_SignUpDateAfter", newDate);
// set local drop downs and hidden input
var dateString = DateUtils.getString(newDate);
dateString = DateUtils.fromUTCToLocal(dateString);
var localDate = DateUtils.getDateFromString(dateString);
DateUtils.setDate("#Reports_SignUpDateAfter_local", localDate);
$("#Reports_SignUpDateAfter_container").datepicker("setDate", localDate);
};
function Reports_SignUpDateAfter_localToUTC() {
// get string and convert to UTC
var dateString = $("#Reports_SignUpDateAfter_local").val();
dateString = DateUtils.fromLocalToUTC(dateString);
$("#Reports_SignUpDateAfter").val(dateString);
// conversion end
}
;
</script>
Problem is when i chose Start and End date like 2015-11-02 and end date 2015-11-04 it always convert me the date to UTC(-1:00h) but it doesn't consider the winter and summer date changes. For that date is should be the same(UTC and local). Is there any clue why is that so ?
var DateUtils = DateUtils || {
getDate: function (selector) {
var value = $(selector).val();
if (value == null || value == "") {
var date = new Date();
date.setHours(0);
date.setMinutes(0);
date = DateUtils.cleanSeconds(date);
return date;
}
return DateUtils.getDateFromString(value);
},
getClientTimeDifferenceFromUTC: function () {
var d = new Date()
return d.getTimezoneOffset();
},
setDate: function (selector, date) {
if (date != null) {
var old = DateUtils.getDate(selector);
old.setTime(date.getTime());
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
} else {
$(selector).val("");
}
},
// copies time from selector and date part from date
copyTimeFrom: function (selector, date) {
var value = $(selector).val();
if (date != null && value != null && value != "") {
var old = DateUtils.getDate(selector);
date.setHours(old.getHours());
date.setMinutes(old.getMinutes());
}
return date;
},
setHour: function (selector, hour) {
var old = DateUtils.getDate(selector);
old.setHours(hour);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
setMinute: function (selector, minute) {
var old = DateUtils.getDate(selector);
old.setMinutes(minute);
old = DateUtils.cleanSeconds(old);
$(selector).val(DateUtils.getString(old));
},
cleanSeconds: function (date) {
date.setSeconds(0);
date.setMilliseconds(0);
return date;
},
// formats date into yyyy-mm-dd hh:mm format
getString: function (date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
month = ('0' + month).slice(-2);
day = ('0' + day).slice(-2);
hours = ('0' + hours).slice(-2);
minutes = ('0' + minutes).slice(-2);
return year + "-" + month + "-" + day + " " + hours + ":" + minutes;
},
// formats string from yyyy-mm-dd hh:mm into date
getDateFromString: function (date) {
if (date == undefined || date == null) {
return null;
}
var m = date.match(/Date\((\d+)\)/); //handle .NET MVC Date format (i.e. "/Date(1426598616621)/")
if (m) {
return new Date(parseInt(m[1]));
}
var year = date.substring(0, 4);
var month = date.substring(5, 7);
var day = date.substring(8, 10);
var hours = date.substring(11, 13);
var minutes = date.substring(14, 16);
var newDate = new Date(year, month - 1, day, hours, minutes);
// newDate.setYear(year);
// newDate.setDate(1);
// newDate.setMonth(month - 1);
// newDate.setDate(day);
// newDate.setHours(hours);
// newDate.setMinutes(minutes);
newDate = DateUtils.cleanSeconds(newDate);
return newDate;
},
// dateString in format yyyy-mm-dd hh:mm
fromLocalToUTC: function (dateString) {
var date = this.fromLocalToUTCDate(dateString);
return this.getString(date);
},
fromLocalToUTCDate: function (dateString) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from local date/time to UTC
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() + offSet;
d.setTime(millis);
// *****
return d;
},
// dateString in format yyyy-mm-dd hh:mm
// returns date as string
fromUTCToLocal: function (dateString) {
var date = this.fromUTCToLocalDate(dateString);
return this.getString(date);
},
// dateString in format yyyy-mm-dd hh:mm
// returns date object
fromUTCToLocalDate: function (dateString, setOffset) {
var dateArray = dateString.substring(0, 10).split("-");
var timeArray = dateString.substring(11, 19).split(":");
if (timeArray[0] == null || timeArray[0] == "")
timeArray[0] = 0;
if (timeArray[1] == null || timeArray[1] == "")
timeArray[1] = 0;
var d = new Date(dateArray[0], dateArray[1] - 1, dateArray[2], timeArray[0], timeArray[1], 0);
// *****
// conversion from UTC to local date/time
if (setOffset != false) {
var offSet = d.getTimezoneOffset() * 60000;
var millis = d.getTime() - offSet;
d.setTime(millis);
}
// *****
return d;
},

Categories