Moment JS add method is returning - javascript

I am using moment.js in Parse cloud code, I need to get an object by tomorrow's date. I am trying to use momentjs to get the day range.
function getTommorowSongQuery()
{
var query = new Parse.Query("Song");
var tommorow = moment().add(1, 'days');
var start = moment(tommorow).startOf('day');
var end = moment(tommorow).endOf('day');
console.log('start = ' + start.toDate() + ' end = ' + end.toDate());
query.greaterThanOrEqualTo("pushDate", start.toDate());
query.lessThan("pushDate", end.toDate());
return query;
}
The problem is that I get the current date (Today) while I expect to get tomorrow.
Any Idea what am I doing wrong.

Related

Using momentjs how to get today's midday

I need to get today's midday.
Please don't confuse the post with another StackOverflow post which says "How to get last midday in moments" which is unanswered and want to get the last date.
I want to get the current date not last
For example:
If today is 2020-05-12T22:00:00 should return 2020-05-12T12:00:00 and that's too in the same time zone.
I'm looking for something preexisting function in the moment if it exists.
Is there any method example: moment().someFunction(12, 'd').
Thanks in advance.
Try using moment-timezone to specify the timezone . Get the start of the day and then add 12 hours to it to give you the desired format
console.log(
moment("2020-05-12T22:00:00")
.tz("America/Los_Angeles")
.startOf("day")
.hour(12)
.minute(0)
.format()
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
Get the start of the current day and add 12 hours in it .
var now = moment()
var startdate =now.startOf('day');
var midday = startdate.add(moment.duration(12, 'hours'));
console.log(midday.toString());
If you want to get the midday in any way you can do it like this. I didn't use moment.js in this example.
function getMidDate(date){
var dateParts = date.toLocaleString().split(":");
var hour = dateParts[0].replace(dateParts[0].split(" ")[1],"12");
var min = dateParts[1].replace(dateParts[1],"00")
var sec = dateParts[2].replace(dateParts[2],"00");
var middateString = hour + ":" + min + ":" + sec + "+0000";
var midDate = new Date(Date.parse(middateString));
return midDate;
}
var date = new Date();
console.log(getMidDate(date));

Date not able to Format(OOP)

The function that I am creating right now is to format the date form the console log to DDMMYYYY instead of the given format. However, I am getting this error where is says the getDate is not a function.
userDate.getDate is not a function
How should I go about solving this error?
function formatDate(userDate) {
let formatted_date = userDate.getDate() + (userDate.getMonth() + 1) + userDate.getFullYear()
return formatted_date;
}
console.log(formatDate("12/31/2014"));
You are using getDate() on a string reference, you need to convert it first to a Date object:
function formatDate(userDate) {
userDate = new Date(userDate);
let formatted_date = `${userDate.getDate()}/${(userDate.getMonth() + 1)}/${userDate.getFullYear()}`;
return formatted_date;
}
console.log(formatDate("12/31/2014"));

How to combine date and time into a single datetime object?

In my react native app i need to combine my date and time in to single datetime object. I used react native modal date time picker npm package for get date and time.
I have a datepicker returning a date string, and a timepicker returning a time string. When i try to combine it will give me a output as Invalid date.
concatDateTime = () => {
var date = this.state.date;
var time = this.state.currentTime;
var dateTime = Moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');
console.log(dateTime.format('YYYY-MM-DD HH:mm'));
}
I need dateobject in ('YYYY-MM-DDTHH:mm:s') format.
You can specify the format of your input string to let moment know how to parse it.
var date = '2019-02-16';
var time = '8:24 PM';
// tell moment how to parse the input string
var momentObj = moment(date + time, 'YYYY-MM-DDLT');
// conversion
var dateTime = momentObj.format('YYYY-MM-DDTHH:mm:s');
console.log(dateTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Just click on below link,
https://stackblitz.com/edit/typescript-bmgx2p?file=index.ts
I hope it will solve your problem.
Another alternative:
let mDate = moment(data.StartDateLocal).tz("Australia/Melbourne");
let mTime = moment(data.StartTimeLocal).tz("Australia/Melbourne");
let x1 = {
'hour': mTime.get('hour'),
'minute': mTime.get('minute'),
'second': mTime.get('second')
}
mDate.set(x1);
this._json.header.transactionStartDateTime = mDate.format("YYYY-MM-DDTHH:mm:ss");

Transforming date which is in seconds to a 'day month year' date

I have a code that works to transform any date which is in seconds to a day month year date. Here it is:
var database = firebase.database();
database.ref(`trips/${userid}/trips/${tripid}/begindate`).once('value').then(photosSnap => {
var tripbegindateseconds = photosSnap.val();
var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
tripbegindatefull.setUTCSeconds(tripbegindateseconds);
var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
var tripbeginday = tripbegindatefull.getUTCDate();
var tripbeginyear = tripbegindatefull.getUTCFullYear();
tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
$('#tripbegindate').html(tripbegindate);
});
I am now trying to implement this into an AngularJS code. I am retrieving data from a Firebase database, and displaying them with AngularJS. Here is my JS code to retrieve the data:
var app = angular.module('test', []);
app.controller('MainCtrl', function($scope) {
var database = firebase.database();
database.ref(`trips/${userid}/trips`).once('value')
.then(photosSnap => {
var trips = [];
photosSnap.forEach((trip) => {
trips.push({
tripKey: trip.key,
tripName: trip.val().name,
tripPhotoUrl: trip.val().photourl,
tripBeginDate: trip.val().begindate,
tripEndDate: trip.val().enddate
});
});
$scope.repeatData = trips;
// apply immediatly, otherwise doesn't see the changes
$scope.$apply();
// returns the array in the console to check values
console.log($scope);
}).catch(err => alert(err));
});
Here my tripBeginDate and tripEndDate variables contain dates in seconds. These are the variables I'm trying to transform into a date with day month year. I don't know how to implement my code into this JS script to make it work.
In fact you could use MomentJS and some Angular wrapper for it (for example, angular-moment on GitHub) in order to do any operation with dates. At least you will "skip" maintaining and debugging your code (keyword: timezones are problematic sometimes).
Since you have a function code for the functionality, just wrap that code into a function like this:
function ConvertDate(DateInSeconds) {
var tripbegindateseconds = DateInSeconds;
var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
tripbegindatefull.setUTCSeconds(tripbegindateseconds);
var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
var tripbeginday = tripbegindatefull.getUTCDate();
var tripbeginyear = tripbegindatefull.getUTCFullYear();
tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
return tripbegindate;
}
and use it on those dates like this:
tripBeginDate: this.ConvertDate(trip.val().begindate),
tripEndDate: this.ConvertDate(trip.val().enddate)
You can Do
var d=new Date(trip.val.begindate*1000) ;//time is in seconds,convert it to miliseconds
d.getMonth();//this will return you month in integer(e.g-january=0 and so on)
d.getFullYear();//this will return you year
d.getDate();//this will return you date
d.getDay();//this will return you day in integer like month
I suggest you to use moment-https://momentjs.com/ where we can parse to any date formats as shown below:
moment(1454521239279).format("DD MMM YYYY hh:mm a") //parse integer

moment.js startOf issue

I am trying to get the start and end of a day (which is a few days from today) using moment.js. This is the code I have:
var today = moment();
var day = today.add(-5, "days");
var startOfDay = day.startOf("day");
var endOfDay = day.endOf("day");
console.log("today " + today.format());
console.log("day " + day.format());
console.log("start " + startOfDay.format());
console.log("end " + endOfDay.format());
And these are the logs:
I2015-11-10T15:19:02.930Z]today 2015-11-10T15:19:02+00:00
I2015-11-10T15:19:02.931Z]day 2015-11-05T15:19:02+00:00
I2015-11-10T15:19:02.932Z]start 2015-11-05T23:59:59+00:00
I2015-11-10T15:19:02.933Z]end 2015-11-05T23:59:59+00:00
As you can see, the start and end dates are exactly the same. The end date is as expected, however, the startOf function appears to be doing exactly what the endOf function does.
Is there perhaps something I am missing?
Dates are mutable, and are altered by the method calls. Your two dates are both actually the same date object. That is, day.startOf("day") returns the value of day both times you call it. You can make copies however:
var startOfDay = moment(day).startOf("day");
var endOfDay = moment(day).endOf("day");
That constructs two new instances.

Categories

Resources