Compare dates in array with different timezones in javascript - javascript

Hello Everyone consider i stored 4 dates in array 2 of them are from different timezone, now if i want to find out the maxdate and mindate in javascript so can anybody please tell me how can i do this ?
Thank you.

for comparing dates with diffrent time zone, you need to convert every date to the same time zone(for example your local time zone) , with that all dates will be in same time zone and you will be able to compare them.
for that you have the "Date constructor" ( new Date() ) that take a date and convert it to your local time zone , after you have this all you need to do is do your logic.
heres an example:
var date1 = new Date("Wed Mar 25 2015 09:56:24 GMT+0900 (Tokyo Time)"); //new Date will take your time string in tokyo and convert it into your local time zone date and so on...
var date2 = new Date("Wed Mar 25 2015 09:56:24 GMT+0100 (W. Europe Standard Time)");
var date3 = new Date(Date.now());
var date4 = new Date(Date.now());
var array = [date1 , date2 ,date3 ,date4 ];
var maxDate = new Date(date1);
var minDate = new Date(date1);
for (var i =1 ; i<array.length ; i++){
if (new Date(array[i]) > maxDate )
maxDate = new Date(array[i]);
if (new Date(array[i]) < minDate )
minDate = new Date(array[i]);
}
alert(minDate.toString() + " " + maxDate.toString());
//Tokyo time is the earliest because is +09:00
//use minDate and maxDate here as you want.

Related

How to construct dateTime today in TypeScript?

I am trying to get DateTime today in TypeScript, here what I do in dart. I tried this in TS let dateNow: Date = new Date(); I didn't find properties to get year, month, day.
This code is in Dart 👇 this is how I get DateTime today in dart.
void main() {
final DateTime now = DateTime.now();
final today = DateTime(now.year, now.month, now.day);
final int todaySinceEpoch = today.millisecondsSinceEpoch;
print(today);
//2021-05-14 00:00:00.000
print(todaySinceEpoch);
//1620930600000
}
Thanks to Rahul Shukla his reply helped me to find the anwer date.toLocaleDateString() returns today's date in string but I wanted to get in object also I wanted the value in milliseconds since epoch.
Here is the final solution.
this returns today date with time
let now: Date = new Date();
this returns today's date without time e.g "Sat May 15 2021"
const todayDate = now.toDateString();
finally this returns today's date in milliseconds since epoch e.g 1621017000000
const todayInMilliseconds = new Date(todayDate).getTime();
To construct Date object here what I did
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
const nowDate: Date = new Date(year, month, day);
or this
const nowDate: Date = new Date(2021, 4, 15);
Month count starts from 0
Since you are using new DateTime() that's why its getMonths(),getYear(), getDate() function is not available
To Get date and time in type script you can use the below code :
> new Date().toLocaleString()
> "5/14/2021, 10:07:07 AM"
To get day, months , years,
var dt = new Date();
var month = dt.getMonth();
var year =dt.getYear();
var day= dt.getDay()
This alone should do it.
let dateNow: Date = new Date();
You can use dateNow.getMonth() to get the just the month field or use dateNow.getUTCFullYear() to get the Year field.
let date: Date = new Date();
console.log("Date = " + date);
Answer:- Date = Tue Feb 05 2019 12:05:22 GMT+0530 (IST)

adding days to historical dates in app script [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
I am trying to pull some historical data, which has a variety of time stamps. I want the use to a user selected date, and then pull all days + some additional days.
Date1 is
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1)
var Enddate = new Date();
Enddate.setDate(startDate + 10);
This doesn't work. I cant seem to figure out how to add the "10 days" to the Date1 variable.
You need the getDate function of the Date object, and you'll need to pass the correct value when instantiating the new Date.
Try this:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1);
// add it to startDate, using getDate()
startDate.setDate(startDate.getDate() + 10);
// now startDate will be 10 days later:
startDate; // Sun Nov 01 00:00:00 GMT-04:00 2020
// if you want an entirely new Date object, then instantiate a new one:
var Enddate = new Date(startDate);
If you want two different variables, then you can use the approach similar to what you tried, like so:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1), second = new Date(Date1); // we're using another temporary variable
// add the days
second.setDate(second.getDate() + 10);
// now use Enddate with this
var Enddate = new Date(second);
Enddate; // Sun Nov 01 00:00:00 GMT-04:00 2020
You can't just add a number to a Date object to get a new date.
You can add to a date by:
getting the current day of the month with getDate()
adding a number of days to that result
setting the new date with setDate()
const Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020";
const addDays = 10;
const startDate = new Date(Date1);
const startDays = startDate.getDate();
const newDate = new Date(startDate);
newDate.setDate(startDays + addDays);
console.log('startDate:', startDate.toISOString());
console.log('newDate:', newDate.toISOString());
Note:
Passing a string into the Date constructor is discouraged, as it produces inconsistent results across browsers.
It is better to pass in the individual date and time values:
const Date1 = new Date(2020, 9, 22, 0, 0, 0);

How to get current month datas from mysql using javascript?

I have table of records and need to get only current month records.
CODE:
let startDate = req.body.startDate
let endDate = req.body.endDate
let result = await caseRegistration.findByDate({ pathology_id : req.body.pathology_id,
created_at: {
'>=': new Date(startDate),
'<=': new Date(endDate)
}
})
Above code I am passing particular dates to get records. But my requirement is If request doesn't have any date then I want to get only current month data. Can you please help me?
var date = new Date();
var firstDay = new Date(date.getFullYear(),date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(),date.getMonth(), daysInMonth(date.getMonth()+1,
date.getFullYear()));
firstDay=>Tue Sep 01 2020 00:00:00 GMT+0530 (India Standard Time)
lastDay=> Wed Sep 30 2020 00:00:00 GMT+0530 (India Standard Time)
Please take care of timezone & date formate you want(it could be any)
If startDate and endDate are empty find first date and last date of current month by using this :
var date = new Date();
var firstDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var endDateOfCurrentMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
Now you can assign these dates to startDate and endDate
statDate=firstDateOfCurrentMonth;
endDate=endDateOfCurrentMonth;

Convert date to UTC by ignoring Daylight Savings javascript

I am in GMT +2 timezone and Daylight saving time on.
My requirement is to ask user a date and convert it into UTC without DST consideration.
when I do console.log(new Date()),
it gives me "Wed Oct 26 2016 18:00:00 GMT+0300 (Turkey Daylight Time)"
I want to send server a UTC format date which server is going to save in Database.
var extractTime = new Date(timeof.edtime); //timeof.edtime contains date given by user.
var d = extractTime.getDate();
var m = extractTime.getMonth();
var y = extractTime.getFullYear();
var h = extractTime.getHours();
var mm = extractTime.getMinutes();
timeof.edtime = moment(new Date(y, m, d, h, mm)).utc().format("YYYY-MM-DD HH:mm");
After converting to utc, timeof.edtime is "2016-09-26 15:00" because it subtract 3 hours to go to GMT. (subtracted 2 hours of standard turkish time) (subtracted -1 of DST)
I want to subtract date to UTC by not considering DST and in our case my expectation is to get hour as "16:00" and not "15:00"
How to convert date to UTC without Daylight saving consideration.
any solution using moment js or jquery will be helpful.
I am testing on chrome.
by browsing through few link it says new Date() will give in standard time and doesn't consider DST consideration but this is not I observed and created plunk to reproduce new Date().toUTCString() consider DST as well, how to avoid subtraction of DST?
https://plnkr.co/edit/tjCOoJqXMHGzCD8B5LdL?p=preview
Inspired by this answer, you could make the time correction as follows:
function compensateDST(dt) {
var janOffset = new Date(dt.getFullYear(), 0, 1).getTimezoneOffset();
var julOffset = new Date(dt.getFullYear(), 6, 1).getTimezoneOffset();
var dstMinutes = dt.getTimezoneOffset() - Math.max(janOffset, julOffset);
dt = new Date(dt);
dt.setMinutes(dt.getMinutes() - dstMinutes);
return dt;
}
// Use your date here:
var extractTime = new Date('2016-10-26 18:00');
// Truncate to minute precision:
var extractTime = new Date(extractTime.getTime() - extractTime.getTime() % 60000)
console.log('Local time:', extractTime.toString());
console.log('UTC time before correction:', extractTime.toISOString());
// Compensate for the DST shift:
var extractTime = compensateDST(extractTime);
console.log('UTC time after correction:', extractTime.toISOString());
try this:
+180 is GMT+0300 (Turkey)
var x = new Date();
var newdate = new Date();
if((x.getTimezoneOffset()) != 180){
newdate = new Date(x.getTime() + (60000*(x.getTimezoneOffset()+180)));
}
console.log(newdate);

Converting milliseconds to a date (jQuery/JavaScript)

I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');

Categories