Momentjs - Add days with specific time - momentjs

I'm using momentjs to calculate certain dates. For example:
moment().add(7, 'days');
This returns date in 7 days in same time like now:
Thu May 21 2020 12:06:35 GMT+0200.
What is the function for adding days but in specific time like:
Thu May 21 2020 17:00:00 GMT+0200.

You could chain the add() to get add hours,minutes,seconds.
console.log('Current time: ', moment().format("DD-MM-YYYY hh:mm:ss"));
var start_time = moment()
.add(1, "days")
.add(4, "hours")
.add(21, "seconds");
console.log('modified time: ', start_time.format("DD-MM-YYYY hh:mm:ss"));
<script src="https://momentjs.com/downloads/moment.js"></script>

I found a solution:
moment({ hour: 17 }).add(7, 'd')
This ads exactly 7 days to today in 17:00:00.

Related

Moment JS diff() returns 0 days between Oct 31 and 1 Nov

As is shown below moment.diff() incorrectly calculates 0 days between yesterday (31 October) and today (1 November). Is this a problem with momentJS or with NodeJS (v14.15.4)?
> a = moment(new Date('2021-10-31'))
Moment<2021-10-31T02:00:00+02:00>
> b = moment(new Date('2021-11-01'))
Moment<2021-11-01T01:00:00+01:00>
> a.diff(b, 'days')
0
> a.diff(b, 'hours')
-24
One possible cause could be the summer => winter change that officially happened from Sun 31 Oct to Mon 1 Nov*. This is evident from the parsing of '2021-10-31' to a summer time Moment<2021-10-31T02:00:00+02:00> (2h).
Nevertheless, I would argue 24 hours diff should not come out as 0 days and thus it's a bug in Moment.
* Though everyone actually sets their clocks back on Sunday 31 Oct... go figure.
I think it's because there was the change of hour and that in .diff() for get the hour it's return a number lower than 1 and moment rounded it at 0.
You can change your code in that without use Date in the moment declaration:
const a = moment('2021-10-31');
const b = moment('2021-11-01');
console.log(a.diff(b, 'days')); // -1
console.log(a.diff(b, 'hours')); // -25 <- but this is wrong
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Or in alternative you can force that .diff() function returns a floating instead of integer putting the third parameter, and after round it like that:
const a = moment(new Date('2021-10-31'));
const b = moment(new Date('2021-11-01'));
console.log(Math.round(a.diff(b, 'days', true)));
console.log(Math.round(a.diff(b, 'hours', true)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Else is to force moment to use the utc date:
const a = moment.utc(new Date('2021-10-31'));
const b = moment.utc(new Date('2021-11-01'));
console.log(a.diff(b, 'days'));
console.log(a.diff(b, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Moment JS getting Date without time [duplicate]

formatCalendarDate = function (dateTime) {
return moment.utc(dateTime).format('LLL');
};
It displays: "28 februari 2013 09:24"
But I would like to remove the time at the end. How can I do that?
I'm using Moment.js.
Sorry to jump in so late, but if you want to remove the time portion of a moment() rather than formatting it, then the code is:
.startOf('day')
Ref: http://momentjs.com/docs/#/manipulating/start-of/
Use format('LL')
Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:
Moment().format('LL'); // => April 29, 2016
The correct way would be to specify the input as per your requirement which will give you more flexibility.
The present definition includes the following
LTS : 'h:mm:ss A',
LT : 'h:mm A',
L : 'MM/DD/YYYY',
LL : 'MMMM D, YYYY',
LLL : 'MMMM D, YYYY h:mm A',
LLLL : 'dddd, MMMM D, YYYY h:mm A'
You can use any of these or change the input passed into moment().format().
For example, for your case you can pass moment.utc(dateTime).format('MMMM D, YYYY').
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 YYYY-MM-DD.
moment().format(moment.HTML5_FMT.DATE); // 2019-11-08
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.DATE); // 2019-11-08
https://momentjs.com/docs/#/parsing/special-formats/
You can also use this format:
moment().format('ddd, ll'); // Wed, Jan 4, 2017
formatCalendarDate = function (dateTime) {
return moment.utc(dateTime).format('LL')
}
Look at these Examples.
Format Dates
moment().format('MMMM Do YYYY, h:mm:ss a'); // December 7th 2020, 9:58:18 am
moment().format('dddd'); // Monday
moment().format("MMM Do YY"); // Dec 7th 20
moment().format('YYYY [escaped] YYYY'); // 2020 escaped 2020
moment().format(); // 2020-12-07T09:58:18+05:30
Relative Time
moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 8 years ago
moment().startOf('day').fromNow(); // 10 hours ago
moment().endOf('day').fromNow(); // in 14 hours
moment().startOf('hour').fromNow(); // an hour ago
Calendar Time
moment().subtract(10, 'days').calendar(); // 11/27/2020
moment().subtract(6, 'days').calendar(); // Last Tuesday at 9:58 AM
moment().subtract(3, 'days').calendar(); // Last Friday at 9:58 AM
moment().subtract(1, 'days').calendar(); // Yesterday at 9:58 AM
moment().calendar(); // Today at 9:58 AM
moment().add(1, 'days').calendar(); // Tomorrow at 9:58 AM
moment().add(3, 'days').calendar(); // Thursday at 9:58 AM
moment().add(10, 'days').calendar(); // 12/17/2020
Multiple Locale Support
moment.locale(); // en
moment().format('LT'); // 9:58 AM
moment().format('LTS'); // 9:58:18 AM
moment().format('L'); // 12/07/2020
moment().format('l'); // 12/7/2020
moment().format('LL'); // December 7, 2020
moment().format('ll'); // Dec 7, 2020
moment().format('LLL'); // December 7, 2020 9:58 AM
moment().format('lll'); // Dec 7, 2020 9:58 AM
moment().format('LLLL'); // Monday, December 7, 2020 9:58 AM
moment().format('llll'); // Mon, Dec 7, 2020 9:58 AM
Whenever I use the moment.js library I specify the desired format this way:
moment(<your Date goes here>).format("DD-MMM-YYYY")
or
moment(<your Date goes here>).format("DD/MMM/YYYY")
... etc I hope you get the idea
Inside the format function, you put the desired format. The example above will get rid of all unwanted elements from the date such as minutes and seconds
With newer versions of moment.js you can also do this:
var dateTime = moment();
var dateValue = moment({
year: dateTime.year(),
month: dateTime.month(),
day: dateTime.date()
});
See: http://momentjs.com/docs/#/parsing/object/.
You can use this constructor
moment({h:0, m:0, s:0, ms:0})
http://momentjs.com/docs/#/parsing/object/
console.log( moment().format('YYYY-MM-DD HH:mm:ss') )
console.log( moment({h:0, m:0, s:0, ms:0}).format('YYYY-MM-DD HH:mm:ss') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
For people like me want the long date format (LLLL) but without the time of day, there's a GitHub issue for that: https://github.com/moment/moment/issues/2505. For now, there's a workaround:
var localeData = moment.localeData( moment.locale() ),
llll = localeData.longDateFormat( 'llll' ),
lll = localeData.longDateFormat( 'lll' ),
ll = localeData.longDateFormat( 'll' ),
longDateFormat = llll.replace( lll.replace( ll, '' ), '' );
var formattedDate = myMoment.format(longDateFormat);
Try this:
moment.format().split("T")[0]
The thing is - you can run into an issue with timezones. For example, if you parse date like this: '2022-02-26T00:36:21+01:00' it may turn into '25/02/2022' As a solution if your date is in ISO format you can just cut off the time portion from the string, like this:
moment('2022-02-26T00:36:21+01:00'.split('T')[0]).utc().format('DD/MM/YYYY')
This solution is quite blunt, so be careful with string format.
This format works pretty fine
const date = new Date();
const myFormat= 'YYYY-MM-DD';
const myDate = moment(date, 'YYYYMMDDTHHmmss').format(myFormat);
Try
new Date().toDateString()
Result - "Fri Jun 17 2022"
This worked perfectly for me:
moment().format('YYYY-MM-DD')
moment(date).format(DateFormat)
Here DateFormat should be DateFormat = 'YYYY-MM-DD'

Moment.js - Parse Date Time Ago

I am saving my date like this in my mongo database:
Thu Oct 25 2018 17:30:03 GMT+0300 (EAT)
I would like to use moment.js to have in the front end like 1 hour ago or 3 hours ago. How would I go about this?
If you're using single locale try
moment('Thu Oct 25 2018 17:30:03 GMT+0300').fromNow(); //eg. 1 day ago, 2 hours ago etc
or
moment('Thu Oct 25 2018 17:30:03 GMT+0300').fromNow(true); //eg. 1 day, 2 hours
for more see docs
and:
you can add your date and then compare with the current time:
const timestamp = moment(dateFromDatabase, 'ddd MMM DD YYYY HH:mm:ss GMT Z').fromNow();
or you can also use diff()
const timestamp = moment(dateFromDatabase, 'ddd MMM DD YYYY HH:mm:ss GMT Z').diff(Date.now(), 'hours');
you can change the measurements using years, months, weeks, days, hours, minutes, and seconds.
For more information, you can take a look on here.

convert the date into a specific format using moment js?

I have an date string as : Wed Aug 30 2017 00:00:00 GMT+0530 (IST) and I want to convert it into like this: 2017-8-30
Now I am doing this:
moment($scope.date.selectedDate).format('YYYY-M-DD') and it is giving the right time but throws a warning as :
moment construction falls back to js date
As the input is JS date so you need to pass input format as well. This can be done by:
moment('Wed Aug 30 2017 00:00:00 GMT+0530', 'ddd MMM DD YYYY HH:mm:ss GMT+-HH:mm').format('YYYY-M-DD');
https://jsfiddle.net/o01ktajp/1/
Relative to the warning you can refer to this post Deprecation warning: moment construction falls back to js Date.
The easiest solution would be to pass the date string in the ISO format.
As for the date, if you simply want to display the date in the UI with that format you can use the 'date' angular filter: https://docs.angularjs.org/api/ng/filter/date.
In your case you could use it like this:
$scope.date.selectedDate | date: 'YYYY-M-DD'
Br,
You can do:
var d = new Date('Wed Aug 30 2017 00:00:00 GMT+0530');
var formated = moment(d).format('YYYY-M-DD');

Find date for same day of the week last year?

OK so for example, today is Tuesday, Feb 02. Well the equivalent "Tuesday" from last year was on Feb 03.
How can I find this out programmatically?
Thanks!!
According to Google, there are 604,800,000 milliseconds in a week. That times 52 should give you the same day of the week a year later (right?).
For example:
var date:Date = new Date(2010, 1, 2);
trace(date);
date.setMilliseconds(date.milliseconds - 604800000 * 52);
trace(date);
Output:
Tue Feb 2 00:00:00 GMT-0800 2010
Tue Feb 3 00:00:00 GMT-0800 2009
Just my two cents. I don't like the idea, that the second answer assumes 52 weeks in a year, it will work for a single year, but is a solution to only this exact problem - eg. if you want to check the same thing moving back 10 years it won't work. I'd do it like this:
var today:Date = new Date();
// Here we store the day of the week
var currentDay:int = today.day;
trace (today);
const milisecondsInADay:uint = 1000*60*60*24;
// Here we move back a year, but we can just as well move back 10 years
// or 2 months
today.fullYear -= 1;
// Find the closest date that is the same day of the week as current day
today.time -= milisecondsInADay*(today.day-currentDay);
trace (today);
returns:
Tue Feb 2 21:13:18 GMT+0100 2010
Tue Feb 3 21:13:18 GMT+0100 2009

Resources