Unix offset with fullCalendar difference - javascript

I want to place a check when I'm getting a momentjs instance through fullCalendar.
I'm at the eventRender callback
var calendar = $('#calendar').fullCalendar('getCalendar');
var atime = calendar.moment();
var atime_h = atime.format("HH:mm");
atime = atime.unix();
var start = calendar.moment(event.start);
var start_u = start.unix();
var start_h = start.format("HH:mm");
console.log(atime);
console.log(atime_h);
console.log(start_u);
console.log(start_h);
Now what that logs is this:
1408024477
15:54
1407888000
00:00
1408024477 == Thu Aug 14 15:54:37 2014 == is correct
But 1407888000 == Wed Aug 13 02:00:00 2014, where I would expect 00:00 instead of 02:00
So there's a difference between the event .unix()/format.() and the moment I created.
Anyone got a clue what's going on?
Edit:
So what happens is that if I create two new moments: moment() and a moment().utc(), I get the same timestamp for both. But when I then display them, there is a difference of two hours.
The .utc one returns two hours in the past, the one without the correct one for me. The timestamp is not two hours back.
But with the event.start (which has _isUTC=true, the timestamp is two hours in the future (!), and it displays it correct when formatted.
So maybe I need to have my event.start to be not UTC and two hours back somehow?
Edit by request in comment, this is what I use now:
var start = calendar.moment(event.start);
console.log(start);
start_utc = new Date(start.year(), start.month(), start.date(), start.hour(), start.minute(), start.second());
var start = calendar.moment(start_utc);
console.log(start);

Try converting your event.start date to utc first, here's how to do it in vanilla js:
start_utc = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
Then you can call .unix() on it and it should give you the expected timestamp.

Related

Conver Timepicker time to utc using Timepicker (ng-bootstrap)

I am using https://valor-software.com/ngx-bootstrap/#/timepicker in my angular project.
I have one task o covert that time to UTC before I request to server.
When I select Time from timepicker value coming is as below.
Now, I have created one function to convert it to UTC using moment.js
static FormatimeSpanBeforeSubmit(date: Date | string ) {
const dateFromTimePicker = date as Date;
// Convert it to format "HH:mm:ss"
let formatedTime = moment.utc(dateFromTimePicker).format('HH:mm:ss');
// Split details in array because I want seconds as always "00"
let list = formatedTime.split(/[\s:]+/);
// Updating last value ""ss" to "00"
formatedTime = formatedTime.replace(new RegExp(list[list.length -1] + '$'), '00');
//Final value
return date ? formatedTime : null;
}
Expected Output : It should convert my time as "9:51:00"
Current Output : "10:54:00"
Please help me and guide me how can I get correct value.
Comment :
(2) As per comments from Hoài Nam I have updated my code like below and in that I am still getting 10:54:00
Please find below two images
i can't comment so i will reply you at here:
i found another solution at here https://stackoverflow.com/a/40381090/9768008
this is what i tried:
var time = 1569326290681; //Tue Sep 24 2019 18:58:10 GMT+0700 (Indochina Time)
var os = new Date().getTimezoneOffset();
var converted = new Date((time + (os * 60 * 1000)));
console.log(converted); // Tue Sep 24 2019 11:58:10 GMT+0700 (Indochina Time)
Issue was date format coming from server was wrong. So, I was getting GMT+ 6.55 instead of GMT+ 8.
Thanks for helping.
Addressed both solution. Mine as well as of #HoàiNam are correct.

Date and time based json element using javascript

I have a json response like this :
{
"NO_INSPECTION": "55",
"NO_SURAT": "00055",
"DATE_OF_DESCRIPTION": "2015-12-21 03:08:24"
}
How can I convert the data in "DATE_OF_DESCRIPTION" Into date and time. Date should be dd-mm-yyy format and time should be in HH:mm format. (A sample value of DATE_OF_DESCRIPTION is 2015-12-21 03:08:24)
I have tried new Date(response.DATE_OF_DESCRIPTION); but no success. How can I achieve this?
Without the use of other libraries and assuming the output will always be zero-padded and the same length, I would do this:
var response = {
DATE_OF_DESCRIPTION: "2015-12-21 03:08:24"
}
var raw = response.DATE_OF_DESCRIPTION;
var datePart = raw.split(' ')[0];
var timePart = raw.split(' ')[1];
var year = datePart.substring(0, 4);
var month = datePart.substring(5, 7);
var day = datePart.substring(8, 10);
var hours = timePart.substring(0, 2);
var minutes = timePart.substring(3, 5);
// NOTE: Month is 0 indexed
var date = new Date(year, month - 1, day);
var dateTime = new Date(year, month - 1, day, hours, minutes);
console.log(date);
console.log(dateTime);
This gives the output
Mon Dec 21 2015 00:00:00 GMT+1000 (E. Australia Standard Time)
Mon Dec 21 2015 03:08:00 GMT+1000 (E. Australia Standard Time)
(I'm from Australia, so your timezone will vary)
JavaScript has a fixed date format and you can change it, thus the Date object won't help you this time. As I see it, you want to split that date, so it's pretty easy if you provide it in this format "dd-mm-yyy HH:mm":
response.DATE_OF_DESCRIPTION = response.DATE_OF_DESCRIPTION.split(" "); // date and time are separated by an space
var date = response.DATE_OF_DESCRIPTION[0];
var time = response.DATE_OF_DESCRIPTION[1];
BTW, if you want to parse a date in a specified format, why don't you use any library for that? Many of them are almost as reliable and fast as native methods. Give them a try ;)
You could also format the date, so it fits the JS specs but, why reinvent the wheel? Libraries will do this for you and you'll get optimal cross-browser results!
I've googled "javascript date parsing library" and this is what I've found:
http://momentjs.com/ <--- I think that's what you're looking for!

javascript - UTC date object manipulation

The UTC thing is really making me crazy... I am trying to have date and time on site in UTC so it has no affect of any timezone.
What I do, I create a date object
var d = new Date();
//convert it to utc
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var utc_date = new Date(utc);
utc_date.setHours(20,0,0)
console.log(utc_date.getTime()) // I want this to be same irrespective of timezone, but don't know why it is changing
Please guide where I am doing wrong..?
UPDATED:
I wanted to create a dropdown of time like on http://jsfiddle.net/HNyj5/ the concept here is I use a timestamp either from client side of selected date or from db and then I generate this dropdown dynamically. So I want the timestamp to be similar on both server/client thats why I am trying to use UTC date object.
You can retrieve the UTC datetime from local time like this (example timezone = GMT+0100):
var currentUTC = new Date; //=>Mon Mar 18 2013 13:53:24
currentUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
//=> currentUTC now: Mon Mar 18 2013 12:54:06
//or
var someUTC = new Date('1998/03/18 13:52'); //=> Wed Mar 18 1998 13:52:00
someUTC.setMinutes(currentUTC.getMinutes()+currentUTC.getTimezoneOffset();
//=> someUTC now: Wed Mar 18 1998 12:52:00
Or as a Date Extension with a one liner:
Date.prototype.UTCFromLocal = function(){
var a;
return new Date(Date.prototype.setMinutes
.call(a = this,a.getMinutes()+a.getTimezoneOffset()));
}
// usage (current date and time = Mon Mar 18 2013 14:08:14 GMT+0100
var d = new Date().UTCFromLocal(); //=> Mon Mar 18 2013 13:08:14
And to retrieve (from a UTC datetime) you could use:
Date.prototype.LocalFromUTC = function(){
var a;
return new Date(Date.prototype.setMinutes
.call(a = this,a.getMinutes()-a.getTimezoneOffset()));
}
Please guide where I am doing wrong..?
You are building a utc_date that is a completely different time, somehow biased by the getTimezoneOffset. Just do
var d = new Date();
d.getTime(); // milliseconds since epoch
or
Date.now();
And if you're working in UTC-land, you should use d.setUTCHours instead of the local-timezone-dependent setHours.
Actually what I was expecting the JS to do was if I pass the timestamp in the Date constructor it should make object w.r.t that timestamp but it converts it to localtimezone which was making issues for me.
So what I did for solving this problem I get the date object by passing the string of the selected date.
var date = new Date(selected_date_str); rather than passing the timestamp
as I was making dropdown of time with UTC timestamp as its value. The start hour:min of dropdown was dynamic, which I was passing as argument in the function, it was from_hr like if I want to create dropdown of time from 20:00 then I pass from_hr = 20
so now I set hour for the selected date
date.setHours(from_hr, 0, 0);
then I made a utc_time variable for making the the value for dropdown
var utc_time = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), from_hr, 0, 0, 0);
this will retain in all timezones, this is what I am going to use as the base. Then in the loop I was adding 15 mins in the time
var count = 0;
jQuery(elem).html('');
while(count <= 95){
var option = '<option value="{0}">{1}:{2}</option>'.format(utc_time/1000, ('0' + date.getHours()).slice(-2), ('0' + date.getMinutes()).slice(-2)); //here i used a format prototype, which you can find in the jsfiddle link of my question
jQuery(elem).append(option);
utc_time += 15 * 60 * 1000; //adding 15 mins in the utc timestamp
date.setMinutes(date.getMinutes() + 15)
count++; }
I was dividing the utc_time with 1000 to make it php compatible, because I was going to retrieve value from here and save in db.

Error in calculating Timezone of Brasilia

function(startDate, lastDate){
var midDate = newDate(startDate.getFullYear(),startDate.getMonth(),Math.ceil((lastDate.getDate() + startDate.getDate()) / 2));
var startDateOffset = startDate.getTimezoneOffset();
var lastDateOffset = lastDate.getTimezoneOffset();
var midDateOffset = midDate.getTimezoneOffset();
var finalDate = new Date();
if(startDateOffset == midDateOffset){
if((lastDate.getDate() - midDate.getDate()) > 1){
alert("loop");
finalDate = this.getDaylightChangeDate(midDate, lastDate);
}
}
I am getting start date as 20 oct , end date as 22nd and mid date again as 20th oct . This is happening only for the location Brasilia , also startDateOffset & midDateOffset is 180 as output.. which is throwing the code in infinite loop as mid date is equal to start date always. Please suggest some other method in javascript to calculate the mid date
There is nothing wrong with your code. The mid date between 2012-10-20T00:00 and 2012-10-21T23:00 is 2012-10-20T23:30. Of course your code can't expect the dates to differ if the input dates are no more than 2 days apart. What would even happen if you passed in the same date as start and end?
If those dates were recorded in different time zones, you always should use UTC to calculate differences.

Javascript convert seconds to a date object

How can I convert seconds into a datetime object in javascript.
Examples:
1.3308313703571
1.6324722385401
This is from a series of points and when they occurred. I understand 1.23323 more then seconds, but I can not change the value, being pulled from an api.
You can try like this:
function toDateTime(secs) {
var t = new Date(1970, 0, 1); // Epoch
t.setSeconds(secs);
return t;
}
Info on epoch date.
You can pass unix timestamp milliseconds as an argument to the Date constructor:
const secs = 30;
const output = new Date(secs * 1000);
console.log(output);
#UVM's answer is helpful, but slightly incomplete if you're dealing with timezones (i.e. UTC vs local time). With timezones, start with UTC using Date.UTC and Date.setUTCSeconds to get a true UTC date and time.
function toDateTime(secs) {
var t = new Date(Date.UTC(1970, 0, 1)); // Epoch
t.setUTCSeconds(secs);
return t;
}
You can then use a library like Moment to convert/format it to a local timezone.
your example values have a decimal.. looking like you are trying to convert 1.something seconds into a date..
Meanwhile check this example here on the correct seconds to date conversion.. you could view their js sources.
The question seems to have already been answered but this may be helpful for those attempting to do something similar to ruby's Time.at() method.
function formatDateTime(input){
var epoch = new Date(0);
epoch.setSeconds(parseInt(input));
var date = epoch.toISOString();
date = date.replace('T', ' ');
return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString().split(' ')[0];
};
I dunno how it be 10 years ago, but now it can solve just doing next:
let sec = 1628618888939
let time = new Date(sec)
let normalDate = new Date(sec).toLocaleString('en-GB',{timeZone:'UTC'})
time: "Tue Aug 10 2021 21:08:08 GMT+0300 (Eastern European Summer Time)"
normalDate: "10/08/2021, 18:08:08"
If in the future u will have problems like this, I can advise read about functions that relate to your question, and solution will come.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources