How to compare Current System date with with another date - javascript

I am getting date in string format from API.
End Date 2014-06-03T06:16:52. I need to write an if-else logic and compare the end date and current date.If end date is less than current date then show customer as In Active and if end date is greater than display the Customer as Active.
I have tried following logic but I am not able to understand and get today's time in string fromat.
this.endDate = this.sampleData != null ?
this.sampleData.customerStartDate : null;
this.currentDate = new Date();
var dd = this.currentDate.getDate();
var mm = this.currentDate.getMonth() + 1;
var yyyy = this.currentDate.getFullYear();
this.currentDate = new Date().toLocaleString()
console.log('End Date', this.endDate);
console.log('Current Date: ', this.currentDate);
if (this.endDate == null) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'In Active';
}
I am getting current date as Current Date: 4/2/2019, 1:23:34 AM
I want to be able to get in same format as End Date.
My main task is to compare the dates how do I achieve it ?

Ideally you want to clean up the date you're getting from an API, and convert it to a JS Date object. You can do this by keeping only the 2014-06-03T06:16:52 part, and giving it to the new Date() constructor.
You can get the current date by calling new Date() without parameters.
You can the turn the dates in to numbers by calling getTime() on each.
You can then compare the numbers.
const incoming_date = new Date('2014-06-03T06:16:52');
const current_date = new Date();
if (incoming_date.getTime() < current_date.getTime() {
// incoming_date is before current_date
} else {
// current_date is before incoming_date
}

as simple as this:
let date=new Date("2014-06-03T06:16:52")
date>new Date()

you could try to express dates in ms since the Unix Epoch with getTime() and compare them
if (currDate.getTime() > endDate.getTime()) {
// set customer to inactive
} else {
// keep customer active
}

I personally like to use moment() for javascript dates. You really just need to have it compare the same format, so you could have something like:
this.currentDate = moment().toISOString();
const dataDate = this.sampleData ? this.sampleData.customerStartDate : null;
this.endDate = moment(dataDate).toISOString();
if (this.endDate > this.currentDate) {
this.customerStatus = 'Active';
} else {
this.customerStatus = 'Inactive';
}

Related

get an array of dates from today for datepicker with Javascript

I am trying to write a function that returns an array of dates from today till the maximum date, so that I can restrict the date picker selection. At the moment I have the following:-
datesAfterToday: function (date) {
var dates = []
var currentDate = new Date()
var endDate = new Date(8640000000000000).getFullYear()
var 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
}
and then I am using Vue.js to mount it as follows :-
mounted () {
this.allowedDates = this.datesAfterToday
},
however I am only getting an array of objects instead of the proper array.
How can I get the proper array of dates so that I can bind it to the allowdates property.
Thanks for your help and time!
For starters new Date(8640000000000000).getFullYear() will set endDate to the year of that date, which is 275760. currentDate will be today's date (in milliseconds), which at the time of me writing is 1511272934156. As you can see currentDate is always greater than endDate, so your while loop never goes to the statements inside.
Another issue is that the date you picked is really far in the future and you're populating an array one day at a time. Your loop will most likely make the page freeze or crash completely. Try picking a date that's more manageable.
For instance, in the snippet below I set endDate by first initializing it to today, then setting the year to exactly one year from now. This gives me an array with roughly 365 values.
You can imagine how big this array would be if I used a year that was 273,748 years in the future.
var dates = []
var currentDate = new Date()
var endDate = new Date()
endDate.setFullYear(endDate.getFullYear()+1)
var 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)
}
console.log(dates)
With all that being said, it looks like you're actually allowed to pass an object specifying the minimum and maximum values rather than an array.
https://vuetifyjs.com/components/pickers#example-6
let d = new Date() // today
let d2 = new Date()
d2.setFullYear(date.getFullYear()+1) // Next year
this.allowedDays = {
min : d.toISOString().substr(0, 10), // e.g. 2017-11-21
max : d2.toISOString().substr(0, 10)
}
Another option would be to use vuejs-datepicker For example:
<script>
var state = {
disabled: {
to: new Date(), // Disable all dates up to specific date
from: new Date(8640000000000000) // Disable all dates after specific date
}
}
</script>
<datepicker :disabled="state.disabled"></datepicker>
See Disabled Dates in the documentation.

Check if time is the same with Moment.js

How to check if time is the same for Moment objects with different dates?
For example I have object like
const endDate = moment().add(30, 'days').endOf('day');
and I want to check if some moment object is endOf day.
private isEndOfDay(dateTime: string) {
const m = moment().endOf('day');
return m.isSame(dateTime, 'minute');
}
const receivedDateFormat: string = 'YYYY-MM-DD hh:mm:ss';
this.isEndOfDay(this.endDate.format(this.receivedDateFormat))
But for this case, when I pass "minute" parameter, it will check minute, hour, day, month and year... which isn't what I want to check.
The part of the documentation that explains that behaviour is
When including a second parameter, it will match all units equal or larger. Passing in month will check month and year. Passing in day will check day, month, and year.
So, if you just want to compare the minutes, you'll need to do something like
endDate.minute() === startDate.minute()
To compare the time only, format() the dates
endDate.format('HH:mm:ss') === startDate.format('HH:mm:ss')
To compare only time part you can set a given date (year, month and day) to your input.
Please note that passing 'minute' to isSame will ignore seconds.
Here a live sample:
function isEndOfDay(dateTime) {
let m = moment().endOf('day');
let m2 = moment(dateTime);
m2.set({
y: m.year(),
M: m.month(),
D: m.date()
});
return m.isSame(m2, 'minute');
}
var endDate = moment().add(30, 'days').endOf('day');
const receivedDateFormat = 'YYYY-MM-DD hh:mm:ss';
var ret = isEndOfDay(endDate.format(this.receivedDateFormat))
console.log(ret);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Another way to to is checking only units that matter for you:
function isEndOfDay(dateTime) {
let m = moment().endOf('day');
let m2 = moment(dateTime);
if( m.hours() === m2.hours() &&
m.minutes() === m2.minutes() &&
m.seconds() === m2.seconds() ){
return true;
}
return false;
}
var endDate = moment().add(30, 'days').endOf('day');
const receivedDateFormat = 'YYYY-MM-DD hh:mm:ss';
var ret = isEndOfDay(endDate.format(this.receivedDateFormat))
console.log(ret);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
See Get + Set section of the docs to see how to get and set units of moment objects.

Moment Js UTC to Local Time

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(date).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
console.log("moment: " + localTime);
No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?
To convert UTC time to Local you have to use moment.local().
For more info see docs
Example:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
Demo:
var date = moment.utc().format();
console.log(date, "- now in UTC");
var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
Try this JsFiddle
To convert UTC to local time
let UTC = moment.utc()
let local = moment(UTC).local()
Or you want directly get the local time
let local = moment()
var UTC = moment.utc()
console.log(UTC.format()); // UTC time
var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time
var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note: please update the date format accordingly.
Format Date
__formatDate: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('D-MMM-Y');
}
Format Time
__formatTime: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('HH:mm');
},
This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:
let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"

How to get current date without time?

I'm trying to get the current date without the time and store it in a variable, within JavaScript. It needs to be without time as I'm converting it to an epoch date, with which I will use to measure the past 24 hours (if date is within 24 hours then it will be displayed). The problem is that with the added time, it doesn't match as within the last 24 hours.
e.g. it returns the date as the following when converted to epoch: 1408704590485
I want it to be like 1408662000000
I'm not to sure how to do this.
Code - How the current days epoch date is currently being stored -
var epochLoggingFrom;
var epochLoggingTo;
$(document).ready(function () {
epochLoggingFrom = dateToEpoch(new Date());
epochLoggingTo = dateToEpoch(new Date());
}
dateToEpoch function -
function dateToEpoch(thedate) {
return thedate.getTime();
}
Try this:
function dateToEpoch(thedate) {
var time = thedate.getTime();
return time - (time % 86400000);
}
or this:
function dateToEpoch2(thedate) {
return thedate.setHours(0,0,0,0);
}
Example : http://jsfiddle.net/chns490n/1/
Reference: (Number) Date.prototype.setHours(hour, min, sec, millisec)
Try this:
var nowDate = new Date();
var date = nowDate.getFullYear()+'/'+(nowDate.getMonth()+1)+'/'+nowDate.getDate();
Note: Adjust format as you want, like reorder day, month, year, remove '/' and get combined date etc.
or use this:
dateToEpoch(new Date().toLocaleDateString())
I tried using javascript. this method returns the current date in "DD/MM/YYYY" format.
getCurrentDate() {
const t = new Date();
const date = ('0' + t.getDate()).slice(-2);
const month = ('0' + (t.getMonth() + 1)).slice(-2);
const year = t.getFullYear();
return `${date}/${month}/${year}`;
}

javascript date validation is not working for today date

I have got below java script code that will validates date range ... when the user entered the today date or any future dates I have set IsValid to true and then will do the save operation ....
for that purpose I have written below code ..
function Save(e) {
var popupNotification = $("#popupNotification").data("kendoNotification");
var container = e.container;
var model = e.model;
var isValid = true;
var compareDate = e.model.DeliveryDate;
alert(compareDate);
var todayDate = new Date();
var compareDateModified = new Date(compareDate)
alert(compareDateModified);
if (compareDateModified > todayDate || compareDateModified === todayDate) {
isValid = true;
}
else
isValid = false;
e.preventDefault();
if (isValid == false)
{
popupNotification.show("Delivery Date should be today date or Greater", "error");
}
$('#Previous').show();
$('#Next').show();
}
Its working fine when I give the future dates but its not working for today date. I also need to check the today's date. I am not able to figure it out the error alert when I try to enter to the today date .
You are comparing two objects of the same type, but different objects, so that will always result in 'unequal'
If you use date.getTime() you will get better results in your comparison - but only if the time component is the same of course.
Think of the Date object like a timestamp. It is based on the unix-style of timestamps (the amount of seconds since 1st January, 1970) so the Date object isn't the day, it is the Date AND the Time.
What you're comparing is the times as well, which could get a little iffy. If only days matter, try using:
fullCompareDate = compareDateModified.getFullYear() + "/" + compareDateModified.getMonth() + "/" + compareDateModified.getDate();
fullTodayDate= todayDate.getFullYear() + "/" + todayDate.getMonth() + "/" + todayDate.getDate();
if(compareDateModified>todayDate||fullCompareDate==fullTodayDate)
{
//Do something
}
This will compare the date and time to make sure they are greater OR check the current date with the compare date (as strings)
Another solution is to blank out the times on both dates:
compareDateModified.setHours(0,0,0,0);
todayDate.setHours(0,0,0,0);
if(compareDateModified>=todayDate)
{
//Do something
}
You are comparing the compareDateModified to todayDate on the millisecond level. To compare at the day level:
var todayDate = new Date();
todayDate.setHours(0,0,0,0);
//you may also have to truncate the compareDateModified to the first
//second of the day depending on how you setup compareDate
if (compareDateModified >= todayDate) {
isValid = true;
}

Categories