momentjs switching between timezone with 12 hours or more difference - momentjs

I am using moment js to convert the date to UTC like this
var a = moment.utc('20-Oct-2021').tz('Asia/Kolkata');
a.format()
This results 2021-10-20T05:30:00+05:30
Now I am trying to use access this from Newsland that is from this timezone Pacific/Auckland - In system I changed my timezone to this which is +13.
Now the result for
moment().utc(a).format() is
2021-10-21T02:09:12Z
If you notice the date is 21 instead of 20 which is the actual date stored.
Facing problem with all greater than +-12

Changing your timezone doesn't change the timezone of a since its zone is manually set. You need to use local() to get the time in your timezone.
// Always pass the string format if the string is not an ISO 8601 date
var a = moment.utc('20-Oct-2021', 'DD-MMM-YYYY').tz('Asia/Kolkata');
console.log(a.format());
console.log(a.utc().format()); // in UTC
console.log(a.local().format()); // This is in your timezone
a.tz("Pacific/Auckland"); // Change to Auckland
console.log(a.format()); // Auckland time
console.log(a.local().format()); // In your timezone, as same as above
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-10-year-range.min.js"></script>

Related

How can I Convert Eastern Standard Date Time to Utc using moment js?

How can I Convert Eastern Standard Date Time to Utc using moment js while my browser time will remain the Pakistan Standard Time
You can use the tz() function to create a date in Eastern Standard Time.
You can then use .utc() to convert this to UTC.
If you want another timezone (say Pakistan) you can use .tz() again to convert:
// Our input time (in Eastern Standard Time).
const inputTime = '2021-09-03 04:45:00';
// Create our moment object in Eastern Standard Time
const easternTime = moment.tz(inputTime, 'EST');
console.log('Times:')
console.log('Eastern: ', easternTime.format());
// Now use .utc() to convert to utc timezone.
const utcTime = easternTime.utc();
console.log('UTC: ', utcTime.format());
// Now use .tz() to convert to Pakistan Standard Time.
const pakistanTime = utcTime.tz('Asia/Karachi');
console.log('Pakistan:', pakistanTime.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

Moment.js, FullCalendar.js datetime comparisons with timezone offsets

I'm confused.
I have a textbox that is populated with a date and time (string) such as '09/07/2021 10:30'.
I convert this string to a moment like so:
var suggestedDateObj = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
I then want to check if this date and time is in between time slots in a fullcalendar.js event object. I do this like so:
var startDateObj = moment(value.start);
var endDateObj = moment(value.end);
if (suggestedDateObj.isBetween(startDateObj, endDateObj)) {}
However...it isn't working. And it's due to timezone offset (i think).
suggestedDateObj returns a value with a UTC offset of +0100 (British Summer Time)
However my calendar event objects return a date with a UTC offset of +0000. So when i check if '09/07/2021 10:30 +0100' is in between '09/07/2021 10:30 +0000' and '09/07/2021 11:30 +0000' it doesn't work!
I guess my question is really either:
How can I create my suggestedDateObj moment with a timezone offset of zero? OR
How can i tell fullcallendar events that the time it is displaying is actually BST (+0100)? At the moment I don't specify the 'Timezone' parameter.
Thanks.
UPDATE
Hmm....this might work....although it feels a bit clunky:
var tmoment1 = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
//create default date with specific timezone offset of zero
var suggestedDateObj = moment().utcOffset(0);
//set the date and time
suggestedDateObj.set({
day: tmoment1.day(),
month: tmoment1.month(),
year: tmoment1.year(),
hour: tmoment1.hour(),
minute: tmoment1.minute(),
second: 0
});
You can generate suggestedDateObj in utc like that:
var suggestedDateObj = moment.utc(suggestedDate, 'DD/MM/YYYY HH:mm');`
For the .isBetween() I suggest you to use the square bracket like forth parameter, like documentation says.
if (suggestedDateObj.isBetween(startDateObj, endDateObj, undefined, '[]'))
The square brackets indicate that the check must include the dates of the limiter

moment toISOstring without modifying date

I have a date like "Thu Sep 01 2016 00:00:00 GMT+0530 (IST)" which I need to send to server as ISO-8601 utc time. I tried like :
moment(mydate).toISOString()
moment.utc(mydate).toISOString()
moment(mydate).utcOffset("+00:00").toISOString()
but I am getting the result like
2016-08-31T18:30:00.000Z
which is 1day behind my intended time. So what can I do to make moment ignore my local timezone and see it as UTC?
Edit:
The expected output is
2016-09-01T18:30:00.000Z
And no, the initial input isn't a string rather a javascript "new Date()" value.
Reason this happens:
This happens because .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()
Solution:
Use the same function and pass true value to it. This will prevent UTC Conversion.
moment(date).toISOString(true)
const date = new Date("2020-12-17T03:24:00");
const dateISOStringUTC = moment(date).toISOString();
const dateISOString = moment(date).toISOString(true);
console.log("Converted to UTC:" + dateISOStringUTC)
console.log("Actual Date value:" + dateISOString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I take the same problem today and find the solution.
Here is the solution: moment(date,moment.ISO_8601)
var date = new Date();
console.log("Original Date");
console.log(date);
console.log("After Moment Format");
console.log(moment(date,moment.ISO_8601));
Test Execution:
Moment Documentation: MomentJs

Joda DateTime output unexpected difference from gmt

My code:
val pattern = "MM-dd-yy"
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)).toDateTime(DateTimeZone.forID("GMT"))
val z = t.getMillis.asInstanceOf[Long]
println("ms= "+z) // expected output: 520560000000 actual output: 520578000000
Several online GMT date converters give a different millis output than DateTime. Anyone know why?
In your solution your local time zone is implicitly used when parsing the date time. You should use
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern).withZoneUTC())
to force the DateTime to be created in the UTC zone. Then, the millis is 520560000000. No need to execute toDateTime(DateTimeZone) on it any more.
Otherwise, with your construction
val t = DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)).toDateTime(DateTimeZone.forID("GMT"))
the DateTime will be first created in your local TZ (ie. midnight of 07-01-86 in your TZ) and then "cast" to UTC, but preserving the timestamp (ie. it will be the same timestamp, but interpreted in UTC, so the time part and the day part will change depending on your local TZ offset).
Example (my TZ is +02:00):
DateTime.parse("07-01-86", DateTimeFormat.forPattern(pattern)) // --> 1986-07-01 00:00 (+02:00)
.toDateTime(DateTimeZone.forID("GMT")) // --> 1986-06-30 22:00 (UTC)
I assumed you are OK with using UTC over GMT but there's also
DateTimeFormat.forPattern(pattern).withZone(...)
where you can provide your desired zone.

Convert datepicker date to ISO format with moment.js

My task is to use a datepicker to pick a date in the prescribed format, eg(MM-DD-YYYY) and pass it to the server as ISO formatted.
While it test the output the ISO formatted date is one day behind.
For example
If i select
07-13-2015
My Output ISO format is
ISO format is :2015-07-12T18:30:00.000Z
Here you can see date is 13 but the output date is 12
I am from India. I tried with zone and utcOffset, ended up with no results. How do i set it right
Here is the JSFIDDLE
js code
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(moment(selectedDate).toISOString());
});
I do have a hidden field which value will be updated on change and that will be processed in the server. No issues on that.
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(selectedDate.toISOString());
});
Your selectedDate is already a moment object so you do not need to feed it back into another moment.
Example:
var test = '07-13-2015'
var mtest = moment(test,"MM-DD-YYYY")
mtest.toISOString()
"2015-07-13T06:00:00.000Z"
Your could try converting the date format to UTC at once.
selectedDate = moment(selectedDate).utc('MM-DD-YYYY')
According to http://dygraphs.com/date-formats.html, if you pass a string like '07-13-2015', it means Midnight of 13th July 2015. Now, if you use toISOString function, it will convert it to UTC by default. To not convert it to UTC, just pass a parameter true in the toISOString function. (Moment.js docs)
For example:
var date = '07-13-2015';
date = moment(date,'MM-DD-YYY');
console.log(date.toISOString(true));
This way, moment will not convert the date to UTC.

Resources