I want to compare two datetime of the same time zone in javascript.
I have tried below code but it's not working due to timezone. I can't get a real local timestamp with timezone.
var createdAt = "2019-07-28T18:14:46+05:30";
var NowTime = new Date($.now());
if(createdAt < NowTime){
$("#sos1").css("background-color","#093");
}else{
$("#sos1").css("background-color","#F03");
}
Convert the datestring to date first using new Date() function
var createdAt = new Date("2019-07-28T18:14:46+05:30");
var NowTime = new Date();
if(createdAt < NowTime){
alert(1);
}else{
alert(2);
}
Related
I am probably making this harder than I need to.
I am using nodejs on the server. The front-end send me the offset.
I need the UTC equivalent of yesterday (or today, last week...), for example, based on offset.
Currently I have:
getYesterday(): DateRange {
const today = new Date();
const fromDate = format(addDays(today, -1), DATE_SERVER_FORMAT);
const toDate = format(today, DATE_SERVER_FORMAT);
return {
fromDate,
toDate
};
}
But this is all based on the server timezone. I need it based on the offset sent from the frontend.
So today needs to be in UTC. So if the offset is 420 (-7) then Yesterday needs to be '2020-05-19 07:00:00.000' to '2020-05-20 07:00:00.000' even if the server is in Guatamala.
My thoughts are to get today's date (not time) in UTC then add (or subtract) the offset. Then use that date to addDays to.
I'd rather not use an additional library.
Gina
I found the answer here: stackoverflow answer
var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());
Which allows me to create "yesterday's" date range:
getYesterday(offset :number): DateRange {
var today = new Date();
today.setUTCHours(0,0,0,0);
today = addMinutes(today, offset);
const fromDate = addDays(today, -1).toISOString();
const toDate = today.toISOString();
return {
fromDate,
toDate
};
}
var date1 = new Date();
var date2 = new Date();
console.log(date2.toUTCString());
console.log(date1.getUTCDate());
<h1>Date UTC +_ 0000</h1>
<pre>
You can see the date of output
console.log(date1.getUTCDate());
and
console.log(date2.toUTCString());
is Same
So the simple way to get UTC Date and Time is in built in Date API
</pre>
And to Manage with time difference or what we can say offset Use following script
var targetTime = new Date();
var timeZoneFromClient = -7.00;
var tzDifference = timeZoneFromClient * 60 + targetTime.getTimezoneOffset();
//convert the offset to milliseconds
//add to targetTime
//make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
console.log(offsetTime);
I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>
//i am checking if given time is lapsed or not compare to current machine time.
//i am not getting alert even time start time and endtime is lapsed.
var currDate = new Date();
var startDate = setTime("09:30:00");
var endDate = setTime("10:15:00");
// given an input string of format "hh:mm:ss", returns a date object with
// the same day as today, but the given time.
function setTime(timeStr) {
var dateObj = new Date(); // assuming date is today
var timeArr = timeStr.split(':'); // to access hour/minute/second
var hour = timeArr[0];
var minute = timeArr[1];
var second = timeArr[2];
dateObj.setHours(hour);
dateObj.setMinutes(minute);
dateObj.setSeconds(second);
return dateObj;
}
// now we can subtract them (subtracting two Date objects gives you their
// difference in milliseconds)
if (currDate - startDate < 0 || currDate - endDate < 0) {
alert("Unfortunately, you can't schedule a meeting in the past.
We apologize for the inconvenience.");
}
In order to check given time is lapsed or not compare to current machine time change the condition as mentioned below.
if (currDate > startDate && currDate < endDate)
{
alert("Unfortunately, you can't schedule a meeting in the past. We apologize for the inconvenience.");
}
It will show the alert if the current time falls in between start time and end time.
Let me know if it worked.
I want to check two dates in java script. date format is YYYY-MM-dd.
var date1 = 2011-9-2;
var date1 = 2011-17-06;
Can anybody say how can I write condition?
If you mean that you want to compare them and your variables are strings, just use == for comparison.
var date1 = '1990-26-01';
var date2 = '2000-01-05';
if (date1 == date2) {
alert('date1 = date2')
}
else {
alert('something went wrong');
}
There are four ways of instantiating dates
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Here is the link to complete tutorial and function of creating, comparing dates http://www.w3schools.com/js/js_obj_date.asp
If you want to compare dates , have a look at the JS date object https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date , in particular the getTime() method .
Assuming the format is YYYY-MM-dd (your second date value breaks this rule) and that they are strings...
var date1 = '2011-9-2';
var date2 = '2011-06-17';
var fields = date1.split("-");
var d1 = new Date (fields[0], fields[1]-1, fields[2]);
var fields = date2.split("-");
var d2 = new Date (fields[0], fields[1]-1, fields[2]);
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
myWin.close()
document.write(startTime);
document.write(endTime);
document.write(timeTaken);
}
hi i want to see the date here "document.write(startTime);".. how can i convert
document.write( new Date(startTime) );
If you check the documentation for the Date object one of the constructors is
new Date(milliseconds)
This way you recreate a Date from the milliseconds passed as argument.
It counts milliseconds since 1 January 1970 00:00:00 UTC.
But keep in mind that the window.open will not wait until the window has loaded before continuing execution of the code. So your startTime and endTime variables will be always pretty close.
Create your startTime with both a time and date and all will be well.
Like this:
var startTime = new Date().getDate();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getDate();
var timeTaken = endTime-startTime;
You can still determine the time difference (elapsed time) between them, but will also have the date available to the end of your routine.
document.write(startTime);
document.write(endTime);
document.write(timeTaken);