How to get time using Moment JS - javascript

I've two javascript variables: startDate and endDate. I want to store the current time(unix timestamp in ms) to endDate and timestamp of 24 hours before in startDate. I'll use this two variables to query the records for last 1 day. How can I do that using moment JS?

Have you looked at the website yet? It's full of examples - http://momentjs.com/ I think what you are trying to do is as simple as
var startDate = moment(endDate).subtract(1, 'days');
Following your question more literally, you can do this:
var endDate = moment(); //the current time
Or, you can just ignore the endDate part of this problem and go straight to startDate with
var startDate = moment().subtract(1, 'days'); //one day before the current time
Finally, if you need to format it a certain way, you can apply a formatting rule such as:
moment().subtract(1,'days').format('YYYY-MM-DD h:mm:ss a')
Use format without an argument and it gives you ISO 8601 format
moment().subtract(1,'days').format() //eg: "2015-04-04T01:53:26-05:00"

This worked for me although I have never found it in the docs. Should have been published but it works.
Try:
moment(currentTime).format("hh:mm"));or
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));

For those who are looking for a way to get timestamp, just do it:
moment().valueOf()

I think what you are looking for is something like
moment(endDate).unix()
which returns something like:
1435161240
You can even calculate the time from now using
moment(endDate).fromNow()
which returns something like:
"2 days ago"

You can directly call function momentInstance.valueOf(), it will return numeric value of time similar to date.getTime() in native java script.

Related

Add time to string data/time

I am trying to pass a time stamp to my API that comes in the format of YYYY-MM-DD HH:MM:SS but i need to manipulate the time to add 5 hours.
Have I done something wrong here? Do I need to convert it to a JavaScript date first?
var manDate = "2020-08-16 16:15:00"
manDate.setHours(manDate.getHours() + 5);
data.manDate = manDate
console.log(manDate)
Expected output - 2020-08-16 21:15:00
When you create a var for date, you need to add the 'new Date()' method.
var manDate = new Date("2020-08-16 16:15:00");
manDate.setHours(manDate.getHours() + 5);
console.log(manDate.getHours());
And to log the hours use getHour() again in the log statement.
Use simpleDateFormat to format the date, then cast the formatted date to calendar and add hours to it.
Try with below code.
SimpleDateFormat sdfObj = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfObj.parse("2020-08-16 16:15:00");
Calendar calendar = sdfObj.getCalendar();
calendar.add(Calendar.HOUR_OF_DAY, 5);
The question was asked to give a solution in java earlier. Below is the answer as per java.
Date newDate = DateUtils.addHours(oldDate, 5);

Comparing a datetime from a get request with the current date time in JavaScript

I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565

Javascript: Set a new Date to tomorrow 8am

I want to make a Javascript date object eg. var now = new Date().getTime() that is set for "tomorrow at 8am", how would I accomplish that?
You could do the following:
var now = new Date();
now.setDate(now.getDate() + 1)
now.setHours(8);
now.setMinutes(0);
now.setMilliseconds(0);
also check this
You could also: var now = Date("2016-03-23T8:00:00");
And var now = new Date(2016,03,23,8,0,0,0 );
If you have a lot of date arithmetics, I can only strongly recommend the use of moment.js.
Using this library, your code would be as short as moment().add(1, 'days').hours(8).startOf('hour').
moment.js works with 'moment' objects that wrap over JS dates to provide additional methods. The moment() invocation returns a moment of the current datetime, thus being the moment.js equivalent to new Date().
From there we can use the moment.js methods, as add(quantity, unit) that adds a duration to the previous date. All these manipulation methods return a modified moment, which mean we can chain them.
The hours() methods is both a getter and a setter depending on its arguments ; here we provide it with a number, which mean we set the moment's hour part to 8. A call to .hours() would have instead returned the current hour part.
startOf(unit) returns a moment at the start of the unit, meaning it will set all lesser units to 0 : moment().startOf('day') would return today's 00:00 am.

Get MongoDB items matching date

I am trying to get a count on posted item from meteor-mongo matching date periods.
I inserted my posts dates as such.
posts
submitted: new Date()
the dates in the database have the following format.
yyyy-mm-dd 16:16:34.317Z // I do not understand the last part (what format it is)
I have tried this to get match the date of today from the submitted field
var currentDate = new Date();
var dd = currentDate.getDate();
var mm = currentDate.getMonth()+1;
var yyyy = currentDate.getFullYear();
var today = yyyy+'-'+mm+'-'+dd;
Posts.find({submitted: today}).count()
However, the last part is returning 0.
Is it because the last hh,mm,ss part of today is missing? If so, how can I tell meteor-mongoto ignore the time part of date so that I can return that count?
I don't like to deal with JS date objects formats, and i guess you either (I do not understand the last part (what format it is))
Give a try to momentjs package, the documentation its pretty clear.
So on the insert you can have something like.
var today = moment().format(''MMMM Do YYYY, h:mm:ss a'); // April 3rd 2015, 12:17:06 pm
Posts.insert({subbmited:today})
and do a simple find like this.
var endQuery = today..add('days', 3).calendar(); // just an example.
Posts.find({submitted: {$gt: today,$lt:endQuery}})
Here thanks to #Larry Maccherone point we are using $gte (grater than) and $lt (less than), so this works like find me post between the post submitted day and the post submitted dat + 3 days (like you ask managing ranges)
You are storing your submitted date in MongoDB with both time and timezone information. Performing a direct comparison of your currentDate with the submitted date in Mongo will never be true, since your currentDate does not contain time information.
Also you are using a String data type to query the date, which also will not work since you need to use a Date data type. Something like this will work for you:
var today = new Date();
today.setHours(0, 0, 0, 0);
Posts.find({submitted: {$gt: today}})
Which will return all the posts with a date greater than midnight of today's date.
Try something like this
posts.find({"submitted": /.*today*/})

Comparing today's date with another date in moment is returning the wrong date, why?

I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');

Categories