Error converting selected date - Angular 8 - javascript

I am making a filter between two dates, Start date and End date, the filter works perfect, it brings the data but it does not bring the complete data and it is because when selecting the dates and converting them to the format, it converts them but one day remains.
This way I am converting the dates:
FiltrarPorFechas(incial, final) {
this.ListaUsuarios = [];
const IniDate = new Date(incial);
const EndDate = new Date(final);
}
associate an image with debug and conversion:
As shown in the image, the initial and final dates arrive at the method thus "2019-07-10" and "2019-07-31" but when I try to convert them it puts them one day less as shown in the image.
I have tried to use moment formatDate and it does not work, I do not understand why and I do not want to add one day.
Somebody could help me ?

You may be potentially having an issue with Timezone. You could reset the time to 00:00:00 either using moment.js or from a normal Date() object.
Now, since your aim is to compare the times, you can use the diff() available from moment.js to achieve this. Please find the sample code below
(function() {
initial = '2019-07-09';
initial_formatted = moment(new Date(`${initial} 00:00:00`));
final = '2019-07-31';
final_formatterd = moment(new Date(`${final} 00:00:00`));
console.log(initial_formatted.diff(final_formatterd, 'days'));
// moment(new Date(`${incial} 00:00:00`)).format('YYYY-MM-DD HH:mm:ss');
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js" integrity="sha256-4iQZ6BVL4qNKlQ27TExEhBN1HFPvAvAMbFavKKosSWQ=" crossorigin="anonymous"></script>
More info
Moment diff()
Date Object set() method

Related

Compare if 2 dates are the same in javascript

var beginningTime = moment('1635750314812', 'YYYY/MM/DD'); // Today date
var endTime = moment(undefined, 'YYYY/MM/DD') // Today date
console.log(beginningTime.isSame(endTime)); //expect true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I am using moment js to get if 2 date are the same using the above pattern. But now i get false instead of true. How to solve the issue?
Instead of formatting the beginningTime and endTime separately, you should take a look at the 'granularity' argument for isSame().
I made a few adjustments to your code for it to work, and also look cleaner.
var beginningTime = moment(1635750314812); // Today date (from timestamp)
var endTime = moment() // Today date
console.log(beginningTime.isSame(endTime, 'day')); //expect true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
It first simply creates a moment of your timestamp and a moment of right now, whenever now is.
Then it will compare the two moments with a granularity of a day, effectively checking if the day and everything bigger (month, year) is the same.

Getting wrong date in Node.js

I tried all the solutions i found here but none work.
Im just trying:
var a = new Date();
console.log(a);
//2020-01-12T05:05:17.320Z
//Time in my timezone: 2020-01-12T02:05:17.320Z
I'm from Brazil, o the timezone is -3:00
I already installed moment.js and tryed:
var moment = require('moment-timezone');
moment().tz("America/Sao_Paulo").format();
var a = new Date();
console.log(a);
but i keep getting whithout my timezone. I also tryed setting the TZ without the moment.js and didn't work.
I cant use some solution that change the way to call the "new Date()" because I have to parse a string to an object that contains Date and I use Prompts module, that get a date from console, that already return a date. I don't know what to do more.
Thanks for any help.
*I'm running on Windows, and the time is right, the configuration is pointing to the right timezone
edit1: more info
The best way that I found was add 'getTimezoneOffset' (minutes) using moment.js
//Will returns the current "wrong" time in formart '2020-09-29T19:47:46.411Z'
//Expect: 2020-09-29T16:47:46.411Z
console.log(new Date())
So if you want see the full date in format ('DD-MM-YYYY HH:mm') of any object
var moment = require('moment')
// specificDay is a Date (type: Object) like '2020-09-22T00:00:00.000Z'
// previously retrieved from the database without information about the time('HH:mm')
// Only with 'YYYY-MM-DD'
moment(specificDay, "YYYY-MM-DD").add(new Date().getTimezoneOffset(),'minute').format('DD-MM-YYYY HH:mm')
You're very close. Moment is a Javascript library that makes formatting time very easy. You are creating your moment object, but you're not outputting it.
I made a very slight change (2nd line) and it works as expected:
var moment = require('moment-timezone');
console.log(moment().tz("America/Sao_Paulo").format());
If you want it formatted nicely, see this page: https://momentjs.com/.
For example:
console.log(moment().tz("America/Sao_Paulo").format('lll'));
// output: Jan 12, 2020 2:45 AM
How does it work?
moment() creates a time object (just like new Date(), but it's moment's special time object). .tz() is calling the timezone function and we give it your time zone as a string "America/Sao_Paulo". .format() then outputs it in a nice custom string. console.log() outputs the whole string to the screen.
Node takes UTC timestamp
https://www.google.com/search?client=firefox-b-d&q=current+utc+time+online
So you can convert to a locale string and after that create a new date. This is a example for mexico city
let mx = (new Date()).toLocaleString('se-SE',{ timeZone: 'America/Mexico_City'}) + "Z";
return new Date(mx);

moment.js compare times with no dates

Is there an easy way in moment.js to compare times with no date attached?
It works when I have a full ISO object with date+time, but not when it's only a time.
For example, this basic code doesn't work because, I presume, it expects a date in the value:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore('12:00:00'));
I understand that I can just add an arbitrary date in there, but what is the elegant way to do this?
Update:
This works from the comment below by #RichardHamilton:
var time_obj = moment(active_time_format, "HH:mm:ss");
console.log(time_obj.isBefore( moment('12:00:00', "HH:mm:ss") ));

Moment.js comparing to times range with am pm

I have an dates array which has an array of appointment times in each date. I loop through a given date to get the appointment times like this :
var newdate = moment(appdate).format('DD/MM/YYYY'); //eg newdate is 04/04/2016
var newtime = moment(apptime).format('h:mm a');
appointmentArr[newdate].forEach(function(value, key) {
console.log(value); //these are all the appointment times for 04/04/2016 eg 11:22:00 AM
});
My question is, how can i check with moment.js, if "newtime" and "value" are within XX mins of each other? ive looked in the docs and on other posts but cant get it right with the AM PM formatting i am using.
To compare two dates with MomentJS you can use moment.diff, and you can specify the unit of measure you want your result in:
newDate.diff(oldDate, 'minutes');
You can then compare that value with your threshold and profit!
EDIT: But you should not format the date before comparing it, since format returns a string. Keep your moment object intact, and format it whenever you need to display it (or save the formatted string in another variable).

Moment.js Convert Local time to UTC time does work

I would like to use Moment.js to convert a local time to UTC equivalent. I believe that I have the correct method in place, but it does not alter the time.
I'm in Sydney Australian +11 and expect the UTC time to be 11 hours earlier.
Internally on the moment object the isUTC flag changes from false to true, but the time does NOT shift, am I meant to use a different technique for this.
How do I actually get the current UTC date out of this object
Before Conversion
var val = '18/03/2015';
var selectedDate = moment(val, 'DD/MM/YYYY');
After Conversion
var a = selectedDate.utc()
I just tried this code and it seems like I get the correct UTC time. I guess I just want to confirm that what I am doing is correct way to access the UTC time from moment.js
a.format("YYYY-MM-DD HH:mm:ssZ")
I found that my usage pattern of in my application was incorrect
selectedDate.utc().format(fullFormat)
It should have been
moment.utc(selectedDate).format(fullFormat)
This works
moment(date_to_convert).utc().format("YYYY-MM-DD HH:mm:ss");
The question is old, but I also faced it. It may be useful to someone:
Using the method of utcOffset() to calculate the UTC time:
selectedDate = (moment(selectedDate).add(-(moment().utcOffset()), 'm'));
And explicitly specify UTC:
selectedDate = moment.parseZone(selectedDate).utc().format();
This is how you do it using moment-timezone
moment.tz(localDate, localTimeZone).utc()
This worked for me !!
selectedDate = moment(selectedDate).add(moment(selectedDate).utcOffset(), 'm').utc().format()
Create a local moment object from you local time and convert it to UTC then format it, then create a new UTC moment from that formatted UTC string
var localDateString = '24/04/2019';
var localDateStringFormat = 'DD/MM/YYYY';
var utcMoment = moment.utc(moment(localDateString, localDateStringFormat ).utc().format('YYYY-MM-DD HH:mm:ssZ'))
console.log(utcMoment);
<script src="https://momentjs.com/downloads/moment.js"></script>
After few frustrating hours, I found what was the problem
Short Answer: To convert time to utc, we need to use format()
Long Answer: Take the example
moment.utc(1559586600000).format('LLL')
.utc sets the isUTC flag to true.
When logging the date, the d key always shows the time in local timezone. (Which makes us believe its not working properly - as shown in your screenshot)
But we need to use .format to get the date/time in UTC format.
The above code returns June 3, 2019 6:30 PM which is the correct UTC time.
const moment = require('moment-timezone');
const dateTime='2020-12-21'
const timezone='America/Anchorage'
const dateTimeInUtc = moment(dateTime).tz(timezone).utc().format();
console.log('dateTimeInUtc',dateTimeInUtc);
const moment = require('moment-timezone');
const dateTime='2020-12-21'
const timezone='America/Anchorage'
const dateTimeInUtc = moment(dateTime).tz(timezone).utc().format();
console.log('dateTimeInUtc',dateTimeInUtc);
After few frustrating hours, I found what was the problem
Short Answer: To convert time to utc, we need to use format()
Long Answer: Take the example
moment.utc(1559586600000).format('LLL')
.utc sets the isUTC flag to true.
When logging the date, the d key always shows the time in local timezone. (Which makes us believe its not working properly - as shown in your screenshot)
But we need to use .format to get the date/time in UTC format.
The above code returns June 3, 2019 6:30 PM which is the correct UTC time.

Categories