I'm trying to compare given date with current date, It is working fine for Indian timezone but other time zones getting one day off. I have went through similar type of issues and there suggestions are like convert UTC string. After converting UTC string getting correct date while console but when comparing not get correct result.
Here my given date in the format like 'YYYY-MM-DD'.
The initial comparison was like below, and this will work fine for Indian timezone.
const datestring = '2019-05-06';
const q = new Date();
const m = q.getMonth();
const d = q.getDate();
const y = q.getFullYear();
const currentDate = new Date(y, m, d);
const givenDate = new Date(datestring);
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
}
The above one will work fine for Indian time zone and for some other time zone apart from Indian time zone, it is giving one day less.
But after converting to UTC like:
const givenDate = new Date(datestring).toUTCString();
Now this will give correct date but for comparing purpose I have converted both current date also to UTC string, by that time result is not coming as expected. I know there are number of articles existed related to this but not getting proper way so only posting this question.
The difficulty is that new Date() will create a date in YOUR timezone. For me, since I'm SAST (+2 hours), if I say new Date(2019, 4, 6) I will get the UTC datetime 5 May 22:00 2019. This makes it difficult to compare dates, since someone in India who wanted to compare "6 May 2019" will actually get a UTC date 6 May 2019, and that won't equal 5 May 2019.
Instead use Date.UTC(year, month, day) - an epoch time is number of milliseconds since 2970, Jan 1st in UTC.
const today = new Date()
const todayYear = today.getFullYear()
const todayMonth = today.getMonth()
const todayDay = today.getDate()
const todayUtc = Date.UTC(todayYear, todayMonth, todayDay)
const dateString = 'yyyy-mm-dd'
const dateArr = dateString.split('-')
const dateUtc = Date.UTC(dateArr[0], dateArr[1], dateArr[2])
if (todayUtc === dateUtc) {
// ...
}
You can use getTime to do the comparaison:
// ...
const currentDate = new Date(y, m, d).getTime();
const givenDate = new Date(datestring).getTime();
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
Related
Here's the code that I have right now:
const moment = require('moment')
const m = moment
const currDay = m().format('D')
const dayOfWeek = m().format('dddd')
const daysInMonth = m().daysInMonth()
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');
I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example: Wed 8, Thu 9, Fri 10 ... Fri 31.
I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...
const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.
function getMonthEnd(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
function getMonthDaysLeft(date = new Date()) {
return getMonthEnd(date).getDate() - date.getDate();
}
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);
To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:
function getMonthDaysLeftAsList(date = new Date()) {
let d = new Date(+date);
// Formatter
let f = new Intl.DateTimeFormat('en',{
day: 'numeric',
month: 'short'
});
let m = d.getMonth();
let dayList = [];
while (d.getMonth() == m) {
dayList.push(f.format(d));
d.setDate(d.getDate() + 1);
}
return dayList;
}
console.log(getMonthDaysLeftAsList());
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)
How do I combine these variables in my code :
var date1 = "13:38";
var date2 = "2019-05-14T00:00:00"
I want to add the time from date1 to date2, so the result should be "2019-05-14T13:38:00"
It's not clear what you are trying to do. If the date and time timestamp always has a time of 00:00:00 and you just want to update the time component, you can do that as a string.
Since "2019-05-14T00:00:00" has no offset, it should be parsed as local, so will represent a different moment in time for each different location with a different offset. If it should be parsed as UTC, please make that clear in the OP. It's fairly easy to go either way, you just have to make it clear how it should be treated.
I've allowed for an optional seconds component.
var date1 = "13:38";
var date2 = "2019-05-14T00:00:00";
let [h, m, s] = date1.split(':');
console.log(date2.substring(0,11) + h + ':' + m + ':' + (s||'00'));
However, if the date and time timestamp also has a non–zero time component and you need to add time, a Date object can make life easier:
// Parse ISO 8601 timestamp in YYYY-MM-DDTHH:mm:ss format
// Assumes no offset, parses as local
function parseDateTime(dt) {
let [Y, M, D, h, m, s] = dt.split(/\D/);
return new Date(Y, M-1, D, h, m, s);
}
// Add time in hh:mm[:ss] format to a date
// Returns a new date, doesn't modify date passed in
function addTime(date, time) {
let [h, m, s] = time.split(/\D/);
let d = new Date(+date);
d.setHours(d.getHours() + +h,
d.getMinutes() + +m,
d.getSeconds() + +m);
return d;
}
let date1 = "13:38";
let date2 = "2019-05-14T03:42:28";
let d = parseDateTime(date2);
let e = addTime(d, date1);
// UTC timestamp in ISO 8601 format
console.log(e.toISOString());
Note that in the second example, the displayed value uses the built–in toISOString method that shifts the offset to UTC (+0). If you want the ISO format but in the local timezone, then you can manually format the string. There are lots of questions and answers on how to do that.
There are also numerous libraries that can help. Since the Date object hasn't changed much in over 20 years, any that have been around a while should be OK.
You will have to parse the first timesting and construct a new date object from it. You should construct a UTC object and pass that into the constructor.
For the second datestring, you will need to add the Zulu token to the end to donate a UTC time and make it ISO 8601 compliant.
After you have your two date objects, update the minutes and hours of the second date object, because that one already stores date information.
const date1 = "13:38";
const date2 = "2019-05-14T00:00:00";
const dateObj1 = (tokens =>
new Date(Date.UTC(0, 0, 0, tokens[0], tokens[1])))
(date1.split(':'));
const dateObj2 = new Date(date2 + 'Z');
dateObj2.setUTCMinutes(dateObj2.getUTCMinutes() + dateObj1.getUTCMinutes());
dateObj2.setUTCHours(dateObj2.getUTCHours() + dateObj1.getUTCHours());
console.log(dateObj2.toISOString().substring(0, 19)); // 2019-05-14T13:38:00
If you want to do this in Moment, you can try the following:
const date1 = "13:38";
const date2 = "2019-05-14T00:00:00";
const moment1 = moment.utc(date1, 'HH:mm');
const moment2 = moment.utc(date2)
.add(moment1.minutes(), 'minutes')
.add(moment1.hours(), 'hours')
console.log(moment2.format('YYYY-MM-DDTHH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}
How can i convert day date (for example, 22 which stands for 1/22/2017) to Unix Timestamp (after conversion result needs to be 1485079018) in javascript.
I tried code below without luck.
var d = new Date();
var n = d.getDate();
var g = Math.round(new Date().getDate()/1000);
to Unix Timestamp (after conversion result needs to be 1485079018
The Unix timestamp 1485079018 is Jan 22 2017 at 09:56:58 UTC. Where are you getting that 09:56:58 from?
In terms of the problem, if I assume you actually want midnight UTC rather than 09:56:58, see comments:
var day = 22;
// Create the date (in UTC)
var dt = new Date(Date.UTC(2017, 0, day));
// Or not UTC, but then we get really far afield of Unix timestamps:
//var dt = new Date(2017, 0, day);
var ts = Math.round(dt / 1000);
console.log(ts);