Moment version: 2.0.0
After reading the docs, I thought this would be straight-forward (Chrome console):
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = startdate.add(moment.duration(2, 'hours'));
returned_endate == expected_enddate // false
returned_endate // Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}
This is a trivial example, but I can't even get it to work. I feel like I'm missing something big here, but I really don't get it. Even this this doesn't seem to work:
startdate.add(2, 'hours')
// Moment {_i: "2013-05-09T00:00:00Z", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array[7]…}
Any help would be much appreciated.
Edit:
My end goal is to make an binary status chart like the one I'm working on here:
http://bl.ocks.org/phobson/5872894
As you can see, I'm currently using dummy x-values while I work through this issue.
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.
So I found the below mentioned way to do the same.
We can add any duration(hour,minutes and seconds) in our current time by moment:
var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format
var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes
var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format
It fulfills my requirement. May be it can help you.
For people having a startTime (like 12h:30:30) and a duration (value in minutes like 120), you can guess the endTime like so:
const startTime = '12:30:00';
const durationInMinutes = '120';
const endTime = moment(startTime, 'HH:mm:ss').add(durationInMinutes, 'minutes').format('HH:mm');
// endTime is equal to "14:30"
Related
I want to get variable to save image name format using the date.
I use this following code.
const time = new Date().toJSON().slice(0,10).replace(/-/g, '');
My expected variable is 20220629. Because my local time is June 29, 2022.
But, the result variable is 20220628. I think this result time using UTC time.
Update:
I try to using JS method like toLocalDateString() and get local time.
const time = new Date().toLocaleDateString().replaceAll('/', '');
But the result is 29062022 not 20220629.
Can anyone help me how to convert into localtime? Thank you.
The date functions rely a lot on system settings to get your local date and time. If you're in the U.S. that happens to be month/day/year.
You simply need to deconstruct it to get what you're looking for. The below code will get it in the order you're looking for (and account for the month being 0-indexed):
const time = new Date()
const time2 = '' + time.getFullYear() + (time.getMonth() + 1) + time.getDate().toString().padStart(2,'0')
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I tried to make null date.
so I tried to make them all 0 when I click the clear button.
this.clear = function () {
_this.newQuarters.forEach(function (_value, index) {
_value.startDate = 0;
_value.endDate = 0;
_value.suppressAllocation = false;
_value.quarters.forEach(function (_childValue, index) {
_childValue.startDate = 0;
_childValue.endDate = 0;
_childValue.suppressAllocation = false;
});
});
};
}
After that, I tried to add 0 at moment from other function.
this.newQuarters.forEach(function (_value, index) {
var startDate = moment(_value.startDate);
but, it display startDate = Wed Dec 31 1969.
Please help me to find to make all date are null.
When passing a number to the moment() function, it interpret it as a unix timestamp.
Which is the number of second since EPOCH time, or 01-01-1970.
So passing 0 to that function result in the very first second of jan 1 1970. As Bergi pointed out, you are probably displaying your dates in your local timezone, which could result in a time before 01-01-1970.
If you want to create a null date, you should set your startDate to null and handle it correctly ( with an if statement).
You could also set the date back to the current time by passing no argument to the moment() function.
Dates can be tricky to work with in an application. There is no such thing as time that is not time. At least not in the world of programming. For this reason we have to create our own understanding of what a lack of time will be.
There is no time without time but there is a lack of value.
You obviously understand this, you had an approach, in your case, you seem to be fine with simply having time be zero, it just broke when working with moment as moment is using EPOCH time. Thus, zero is time.
You are going to have to test like the rest of us.
this.newQuarters.forEach(function (_value, index) {
var startDate = _value.startDate ? moment(_value.startDate) : null;
Lack of time could be whatever you want, undefine, null, a beginning date
Be consistent: Database vendors and languages handle things differently, front end is not always the same time zone, etc.
If you are dealing with momentjs library, there is a function: invalid()
You can easily make your variables invalid moment object and control their validity.
let currentDate = moment(); // Valid moment object
console.log(currentDate.format());
// make the moment object invalid
currentDate = moment.invalid();
console.log(currentDate.isValid()); // Check validity
console.log(currentDate.format()); // Invalid date
// make the moment object valid again
currentDate = moment();
console.log(currentDate.isValid()); // Check validity
console.log(currentDate.format()); // A valid date
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
I'm a software engineering student in an Intro to JavaScript course and I'm stuck on an assignment. Here's the assignment,
in a file named alarmTime.html, use prompt() to find out how long the user wishes to nap. Then, write a statement to the document telling the user what time her/his alarm should go off. Be sure the times are local for the user.
I'm stuck on adding the input to the user's local time. I don't really know what I'm doing wrong and I'm having difficulty understanding what to do because all I'm getting is what seems to be random numbers. Please take a look at my code and point me in the right direction.
var howLong = prompt("How long, in hours, do you want to nap for?", 1);
var parsedInput = parseFloat(howLong);
var today = new Date();
var currentTime = today.toLocaleTimeString();
var myHour = today.getHours(currentTime);
var alarm = today.setHours(myHour + parsedInput);
document.write(alarm);
The reason is because of this statement document.write(alarm);. setHours method in Date object updates the Date instance, and returns the Date in milliseconds. Therefore, you are printing the Date object as the number of milliseconds since January 1, 1970. To fix that, simply replace it with document.write(today);
The problem is var alarm = today.setHours(myHour + parsedInput);
instead try to set the variable as
var alarm = today.getHours();
or change document.write(alarm); to document.write(today);
Date.now() will give you current time (users local time). Add time from prompt and your good:
let napTime = prompt('how many minutes do you want to nap?');
let alarmTime = new Date(Date.now()+napTime*60000);
//if you want to get HOURS instead of minutes
//let alarmTime = new Date(Date.now()+napTime*3600000);
//print it out. toLocale...() functions return local FORMAT of the datetime,
//they dont deal with timezones
document.write('set alarm to '+alarmTime.toLocaleTimeString('en-US'));
console.log(alarmTime);
Im trying to create a JavaScript function that is storing some information in firebase Database each time it is called. One information that I want to store is the current Date and Time that the function has been called. I’ve create something on my own but the formation of the date and time isn’t quite how I want it to be. My source code of the function is the following:
function AddtoDatabase(id,title,description){
var rootRef = firebase.database().ref().child(`notifications/${id}`);
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
rootRef.push({
title:`${title}`,
description:`${description}`,
//time:`${new Date().toISOString().split('T')[0]}`
time:`${(new Date(Date.now() - tzoffset)).toISOString().slice(0, -1)}`
});
}
Using the source code above i get the following result from date and time:
How can I edit the code to get just
Received at:2018-03-14 09:48
Can anyone please help me?
I think that you can achieve this simply using the Date() object's native methods like getFullYear(), getFullMonth() etc.
Here's the code.
const date = new Date();
const year = date.getFullYear();
const month = date.getFullMonth() + 1 // months start from 0
const day = date.getDay()
const hour = date.getHours();
const minutes = date.getMinutes();
const time = `Received at ${year}-${month}-${day} ${hour}:${minutes}`;
You should use the moment library for the formatting: https://momentjs.com/
In particular, look at this part of the documentation: https://momentjs.com/docs/#/displaying/
So in your case you would do:
moment().format("YYYY-MM-DD hh:mm");
Also, a best practice is to store in your database the number of milliseconds since 1970/01/01, which you can obtain through the JavaScript getTime() method
In my project my scheduling to post in social network sites using cron job,
timestamp value should end with zero instead of 1.
here is the node js code used:
var rule = new cron.RecurrenceRule();
rule.second = 0;
cron.scheduleJob(rule, function(){
var now = new Date();
var date = dateFormat(now, "dd-mm-yyyy, h:MM:ss TT");
console.log(Math.floor(new Date()/ 1000));
retrivepost(Math.floor(new Date()/ 1000).toString());
});
here is the timestamp value output log which i get in terminal
1517894101
1517894161
1517894221
1517894281
1517894341
1517894401
1517894461
1517894521
1517894581
1517894641
1517894701
1517894761
1517894821
1517894881
1517894941
1517895001
1517895061
1517895121
For me your code works just fine and logs timestamps ending with the zero second just like scheduled.
However, I think if your retrievepost() function depends on a timestamp being on the minute exactly you should round your date inside the .scheduleJob function to the nearest minute. A whole second later seems odd to me but imagine that you have some code just above that takes a while to compute. retrievepost() will fail then, even if you get it working right now.