remove timezone in my random date generator in javascript - 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}";
}

Related

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

Calendar to show today's current date with the next 60 days

I have created a calendar that successfully displays todays current date. It also shows the remaining months however I am trying to change the functionality of the calendar so that it only shows the next 60 days from today's current date.
The code so far:
var todayDate = new Date();
var finalDate = new Date(todayDate)
finalDate.setDate(todayDate.getDate() + 60)
var dayNumber = todayDate.getDate();
var month = todayDate.getMonth();
var year = todayDate.getFullYear();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var calendarTable = document.getElementById("calendar-body");
document.getElementById("month").innerHTML = months[month];
document.getElementById("year").innerHTML = year;
function createCalendar(month, year) {
var firstDay = new Date(year, month).getDay();
var totalDays = daysInMonth(month, year);
blankDates(firstDay);
for (var day = 1; day <= totalDays; day++) {
var cell = document.createElement("li");
var cellText = document.createTextNode(day);
if (
dayNumber === day &&
month === todayDate.getMonth() &&
year === todayDate.getFullYear()
) {
cell.classList.add("todays-day");
}
cell.setAttribute("data-day", day);
cell.setAttribute("data-month", month);
cell.setAttribute("data-year", year);
cell.classList.add("singleDay");
cell.appendChild(cellText);
calendarTable.appendChild(cell);
}
}
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
function blankDates(count) {
for (var x = 0; x < count; x++) {
var cell = document.createElement("li");
var cellText = document.createTextNode("");
cell.appendChild(cellText);
calendarTable.appendChild(cell);
}
}
createCalendar(month, year);
Any ideas would be great. Thanks :)
First you need to find the number of dates between two dates,
In this case is finalDate and todayDate
var diff = Math.floor(( Date.parse(finalDate) - Date.parse(todayDate)) / 86400000);
You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000
The output of the diff now is 60
Then you add the diff variable into the for loop.
Woking example
Just an idea.
But you could generate an array of the dates between now and 60 days.
Then loop through that array to build the calendar.
This way the Date functions can be used for each date in the array.
Here's a simple function to generate such array.
function getDateRange(pStartDate, pDays) {
let days = pDays || 1;
let dates = [];
let n = 0;
let startDate = new Date(pStartDate.toISOString().slice(0,10));
let endDate = new Date(startDate.getTime() + (days * 86400000));
do {
dates.push(new Date(startDate.getTime() + (n * 86400000)));
n++;
} while (n <= days);
let obj = {
startDate : startDate,
endDate : endDate,
days : dates.length,
dates : dates
}
return obj;
}
var dateRange = getDateRange(new Date(), 60);
console.log(dateRange.dates);

JavaScript: How to get simple date without timezone

I have code that generates random dates in a date range, which gives me dates which, when logged, produce this format:
Wed Sep 25 2019 05:00:00 GMT+0500 (Pakistan Standard Time)
I just want to get the date without timezone and Day specifically like this:
2019-09-25
I am trying to get random dates between specified dates using the following code:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //YYYY-MM-DD
var getDateArray = function(start, end) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length, temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
return arra1; }
console.log(shuffle(dateArr));
It's not a duplicate question as I was trying to achieve different and very specific formate.
One solution would be to map each item of arra1 through a custom formating function (ie formatDate()) where .getDate(), .getMonth() and .getYear() are used to populate the formatted string:
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}`
}
Some points to consider here are:
Date#getMonth() returns 0-indexed dates in the range of 0-11. To match the desired date format, you should add 1 as shown
Check for day and month values that are less than 10 and prefix a 0 to pad those numbers to obtain the desired formatting
This can be added to your existing code as shown:
var startDate = new Date("2019-08-26"); //YYYY-MM-DD
var endDate = new Date("2019-09-25"); //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) {
var arr = new Array();
var dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
var dateArr = getDateArray(startDate, endDate);
function shuffle(arra1) {
var ctr = arra1.length,
temp, index;
// While there are elements in the array
while (ctr > 0) {
// Pick a random index
index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
ctr--;
// And swap the last element with it
temp = arra1[ctr];
arra1[ctr] = arra1[index];
arra1[index] = temp;
}
/* Update this line */
return arra1.map(formatDate);
}
console.log(shuffle(dateArr));
Use .toISOString() and .substr(). Example:
var dt = new Date("2019-09-25");
console.log(dt.toISOString().substr(0,10)); // 2019-09-25
The advantage of this approach is that the Date object has the .toISOString() method built-in, so you don't have to reinvent the wheel. That method returns a full ISO string, though, like "2019-09-25T00:00:00.000Z". So, you can use .substr to retrieve only the part you want to use.
var getDates = function(startDate, endDate) {
var dates = [],
currentDate = startDate,
addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
while (currentDate <= endDate) {
dates.push(currentDate);
currentDate = addDays.call(currentDate, 1);
}
return dates;
};
// Usage
var dates = getDates(new Date(2019, 10, 22),
new Date(2019, 11, 25));
dates.forEach(function(date) {
console.log(date);
});

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>

Categories