Javascript

JavaScript Dates & Moment.js

By June 17, 2018 August 5th, 2020 No Comments

How to validate a Vuetify dob field for let’s say at least 16 years or 18 years.

Instead of doing a validation later, we can provide the datepicker field with the max. Refer here for the code.

Setting a default date for Vuetify or for toISOString()

Vuetify perhaps expects .toISOString() as default date. Not sure but there is a thing with .toISOString(). Apparently this gives time in UTC. When we pass on a date here the output is always off. E.g. Jan 31st instead of Jan 1st. Solution:

1
var dob = (new Date("1 Jan 1997 UTC")).toISOString().substr(0, 10);

JavaScript Set Default Date for Object

The key thing to remember here is to always pass on the month, the year alone does not work.

1
2
3
4
5
6
let tempDate = new Date();


let dob = new Date(tempDate.getFullYear() - 18, tempDate.getMonth()+1, tempDate.getDate());

let dob = new Date(tempDate.getFullYear() - 18, tempDate.getMonth()).toISOString().substr(0, 10);

Moment set and get

1
2
3
4
5
6
7
8
// Note: when you are working on seconds level. Be sure to specify seconds as well.
moment().set('date', 20).set('hour', 19).set('minute', 35).set('second', 0)

// This is accepted too
moment().set('hour', 19).set('minute', 35)

// This points to current moment / time.
moment()

1
2
moment().get('hour')
moment().get('minute')

Tip #1: Do not use date and MomentJs interchangeably. Use either one of them. Because, some functions like getFullYear will only work on Date object and not for moment. Hence, stick to only one.

  1. A note for parsing custom date to moment

    It is preferred to pass in the format as below whenever possible.

    moment(day.date).format(“YYYY-MM-DD”)
     

Is Today

1
2
// e. date is the current moment clone date object
$scope.isSelectedDateToday = (moment(e.date).isSame(moment(), 'day'));

Compare dates

Is in Past / Is After

1
2
3
4
5
            if (typeof addOnEndDate === 'undefined' || !addOnEndDate) {
                return true;
            } else {
                return moment(addOnEndDate).isAfter(moment());
            }

The addOnEndDate is Something like Aug 03 2020 but works in comparison to today.

IS Same Comparison

1
momentDate.isSame(val.holiday_date, 'day') // val.holiday_date is in format YYYY-mm-dd

Formatting

11: 13 PM


1
moment($scope.minTime).format('hh:mm A')

Tip #2: Tip for angular js bootstrap timepicker: When setting upper and lower limit to timepicker, use 1 minute lesser where making sure interval is may be 5 minutes. This works particularly well with uib-timepicker ()

E.g. minTime to be set to 7:59 instead of 8 AM. 

  1. How to convert a moment object to JavaScript object?
1
moment().toDate();