Dealing With Futre and Past Dates and Times with JavaScript Date Object - javascript

I am trying to get future and past dates programatically based on the current time. I am not sure if I am just dumb or I am truly doing something wrong. So I have 2 questions
Does Node.js or the V8 engine have getMinutes, getMonth, etc... in it? I ask because when I try them I get a has no method errors for each of them with regards to a Date object?
Second question is: is there a resource I have missed on how to deal with dates in Node/V8 that I have just missed somewhere?
At the end of the day I am trying to get a date object that is from an hour ago and an hour into the future. Also 5 minutes ago and 5 minutes in the future. It doesn't seem like it should be that hard, but I have been spinning my wheels for a couple of hours now.
Also do it without a 3rd party javascript module.
Here is one, of many, attempt with little luck:
var d1 = Date();
console.log(d1);
console.log(d1.getMonth());
error:
TypeError: Object Sun May 13 2012 20:28:01 GMT-0500 (CDT) has no method 'getMonth'
Another example this time from REPL: (Should this not be "march 3 2012 at 3:03:03")?
d1 = new Date(2012,3,3,3,3,3)
> Tue, 03 Apr 2012 08:03:03 GMT

When the Date constructor is called as a function, it returns a string, not a date object. Change your code to:
var d1 = new Date();

Related

Why does new Date(dateString) return two different dates on different devices with exactly the same input? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
Knowing that my timezone is GMT+2, consider the following code:
Running On a Selfy 4G phone:
myDate = "2017-05-12T09:00:00";
dateFoo = new Date(myDate); // Fri May 12 2017 11:00:00 GMT+0200 (CEST)
Running on a Galaxy S7:
myDate = "2017-05-12T09:00:00";
dateFoo = new Date(myDate); // Fri May 12 2017 09:00:00 GMT+0200 (CEST)
Why is there an inconsistency in the outputs and how would I go about solving it?
My question is different from other similar questions (such as Why does Date.parse give incorrect results?) because in my case I am using the exact same string and it's the devices that differ.
The initial problem was that Date.parse on one device took my local time as the time zone, whereas on the other device it took UTC.
By appending a Z at the end of my initial dateString, I forced the date to always be considered as UTC no matter what the device, therefore achieving consistent results with Date.parse().
In order to then get the date in my local time, I used the answer to this question: https://stackoverflow.com/a/1486612/1875581.
Diff in your date is because of timezone.
You can try to convert date to UTC date for get perfect result like this.
myDate = "2017-05-12T09:00:00";
dateFoo = new Date(myDate).toUTCString();

moment.js time wrongly calculated

I am using the following in moment.js to convert seconds to Days Hours Minutes Seconds format
moment().startOf('year').seconds(1209600).format('DD HH:mm:ss')
But instead of getting 14 00:00:00, I am getting 15 00:00:00
What am I missing here?
1209600 seconds is 14 days, so because the first day of the year is day 01 00:00:00, if you add 14 days you get 15 00:00:00.
You don't say exactly what you're trying to do, but what you're getting is the right answer for "what's the date/time for 1209600 seconds into the year."
You're attempting to work with the concept of duration, but you're using the calendar to do it. This isn't a good idea for several reasons. As others pointed out, the calendar starts on the 1st, which is throwing you off. But also, you could have local time zone discontinuities affect your results, such as if your duration went far enough into the year to be caught by the spring-forward daylight saving time transition.
If you want to use Moment to work with durations, there is a separate API for that:
var d = moment.duration(1209600, 'seconds');
var h = d.hours();
var m = d.minutes();
var s = d.seconds();
There is currently not a format method built-in for durations, so you'd have to assemble these into a string yourself, applying zero-padding where necessary. However, there is the moment-duration-format third-party plugin, which would let you do it like this:
moment.duration(1209600, 'seconds').format('DD HH:mm:ss')
moment().startOf('year'); // set to January 1st, 12:00 am this year
So, startOf('year') method set moment starting point to 1st January of current year from 12.00 AM
, which is start of the day. and you are adding 14 days on top of that. But as the initial date started at 12.00 AM, its still a whole day (ends at 11.50 PM) which adds one additional day in final result.

DatePicker Error in Angular JS due to UTC

I have selected the 12th of September 2014 in the UI.
Following is the code
ctrl.$formatters.push(function (modelValue) {
console.log(modelValue);
var dt = new Date(modelValue);
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
console.log(dt)
return dt;
});
The two console logs i see are the following.
09/11/2014
Wed Sep 10 2014 18:30:00 GMT+0530 (IST)
Am not sure why the conversion from UTC to local is not carried out correctly.
Thanks in advance.
Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.
Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:
return dt.toLocaleDateString();
If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:
dt.setTime( new Date().getTime() );
instead of the setMinutes(...) line.
then you can
return dt.toLocaleString;
All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

Javascript parsing Times without Date

I need to parse and manipulate Times without Dates in my code. For example i might get the string "15:00" from a timepicker. I want to turn this into a Time object of some kind - I normally work in Python which has distinct Date, Time, and Datetime objects.
However all the solutions i've seen focus on using the Date object. This cannot parse a string like "15:00" since it requires day information. I don't want to add arbitrary Date information to Times - especially since Date appears to make assumptions about things like daylight saving depending on the day and the locale, and there appears to be a risk of it automatically attempting to translate the time into a given locale. Furthermore I want to be able to add times, e.g. "15:00 + 1 hour"
What is the recommended solution to parse and handle "raw" times not associated to dates?
Here's a moment.js solution for 12 or 24 hour times:
moment('7:00 am', ['h:m a', 'H:m']); // Wed Dec 30 2015 07:00:00 GMT-0600 (CST)
moment('17:00', ['h:m a', 'H:m']); // Wed Dec 30 2015 17:00:00 GMT-0600 (CST)
moment('17:00 am', ['h:m a', 'H:m']);// Wed Dec 30 2015 17:00:00 GMT-0600 (CST)
moment('17:00 pm', ['h:m a', 'H:m']);// Wed Dec 30 2015 17:00:00 GMT-0600 (CST)
http://momentjs.com/docs/#/parsing/string-formats/
Unfortunately, there's not a great solution. JavaScript only has a Date object, which is probably misnamed since it is really a date+time.
One thing you might want to think about deeper - you say you want to work with only time, but do you mean a time-of-day or do you mean a duration of time? These are two related, but slightly different concepts.
For example, you said you might want an operation like "15:00 + 1 hour". Well that would clearly be 16:00 either way. But what about "15:00 + 10 hours"? It would be 25:00 if you are talking about a duration, but it might be 01:00 if you are talking about time-of-day.
Actually, it might not be 01:00, since not all days have 24 hours in them. Some days have 23, 23.5, 24.5, or 25 hours, depending on what time zone and whether DST is starting or stopping on that day. So in the time-of-day context, you probably do want to include a particular date and zone in your calculation. Of course, if you are talking about straight 24-hours days, then this point is irrelevant.
If you are talking about durations - you might want to look again at moment.js, but not at the moment object. There is another object there, moment.duration. The reference is here.
And finally, you might want to consider just using plain javascript to parse out hours and minutes from the time string as numbers. Manipulate the numbers as necessary, and then output a string again. But your question seems like you're looking for something more managed.
I ended up using the following since I was already using moment in my app:
var str = '15:16:33';
var d = new moment(str, 'HH:mm:ss');
See Moment String+Format docs for other format strings you can use.
And I know I am over 8 years late to this party, but it is worth noting that moment.js is no longer being developed and is on a pacemaker for maintenance. They actually do NOT recommend using moment.js for new apps.
More details are found here: https://momentjs.com/docs/
I had to do this recently for a project but didnt really need to include moment.js, the method I used was to manually parse the time like this:
function parseTime(time) {
let timeInt = parseInt(time);
let minutes = time.substring(3,5);
// you could then add or subtract time here as needed
if(time > '12:00') {
return `${timeInt - 12}:${minutes} PM`;
} else {
return `${timeInt}:${minutes} AM`;
}
}
Use this as an alternative starter if you don't want to use moment. Note this example uses es6 syntax.
Okay, so I know I'm way late to the party. Like 6 years late but this was something I needed to figure out and have it formatted HH:mm:ss (24 hours).
moment().format(moment.HTML5_FMT.TIME_SECONDS); // 17:44:56
You can also pass in a parameter like, 2019-11-08T17:44:56.144.
moment('2019-11-08T17:44:56.144').format(moment.HTML5_FMT.TIME_SECONDS); // 17:44:56
https://momentjs.com/docs/#/parsing/special-formats/
I know I am writing this 8 years later but it's no longer advisable to use the moment.js library nowadays since it's no longer supported, luxo.js is the preferred(like the evolution of moments.js) one you can find more here: https://moment.github.io/luxon/api-docs/index.html
We know that the Date class in JavaScript must always contain a date, and entering time alone is not enough.
But when asked, I do not need to enter a date. This could mean:
You intend to compare two dates with each other.
The two dates are shared on the same day.
If so, then as a trick, you can add a specific date(any date) to your time as string. (E.g. 0000-01-01 )
For example, this code is incorrect:
var d1 = '00:53:57.123';
var d2 = '00:53:58.124';
console.log(new Date(d2).getTime() - new Date(d1).getTime());
//result: NaN
But this way you can get the right result:
var d1 = '00:53:57.123';
var d2 = '00:53:58.124';
d1 = '0000-01-01 ' + d1;
d2 = '0000-01-01 ' + d2;
console.log(new Date(d2).getTime() - new Date(d1).getTime());
//result: 1001

How to use logic to perform operations only on date objects in an array in Google Apps Script

I am trying to build a script which will read a particular column in a spreadsheet, and only if the item in a particular cell is a date object (which Google scripts automatically renders from our format - MM/dd/yyyy) Google's date object gives all time parameters, as such:
Sat Apr 26 00:00:00 GMT-05:00 2014
I ONLY want the data stored from the column if it is a date object, so what logic would I put in an if() statement to accomplish this? I tried using regularexpressions, as follows
var dateFormat = new RegExp('[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s[0-9]{2}\\s[0-9]{2}:[0-9]{2}:[0-9]{2}\\sGMT-[0-9]{2}:[0-9]{2}\\s[0-9]{4}');
var line = "Thu Dec 31 00:00:00 GMT-06:00 2015";
Logger.log(dateFormat.test(line));
This test returns TRUE. So why does the logic not work directly on date objects?
And if you know about date objects in Apps scripts, where can I find information on operating on date objects. I am interested in detecting a date is 45 days in the future, 30 days in the future, and 15 days, and sending corresponding alerts for these dates coming up, then after 15 days sending an alert every day.
Your test does not work on Date objects because they are Date objects and not String objects.
use the instanceof operator (cellValue instanceof Date) to find out if it's a date.

Categories