Convert the CST time to local browser time [duplicate] - javascript

i am using moment for getting server time .
moment.tz.setDefault("Asia/Kolkata");
var now = new Date();
var _p_date = moment.tz(now, zone).format();
time when inserting _p_date = 2016-01-05T18:32:00+05:30
But in database date variable is type of DATETIME. and time is saved as 2016-01-05 18:32:00.
and after that when i comparing with this to get time_ago funcionality. providing me wrong estimation.
using time ago = moment("2016-01-05T18:32:00.000Z").fromNow(); // is showing In 5 hours

Since your initial timezone is lost you have to create moment.tz object with selected timezone. Try this plunker
var date = moment.tz(moment("2016-01-05T18:32:00.000Z", "YYYY-MM-DDTHH:mm")
.format('YYYY-MM-DD HH:mm'), 'Asia/Kolkata');
console.log(date.fromNow());

Related

Set Hours in Date() to 0 [duplicate]

i am trying to get current date to compare and setting hours to zero but still getting time.
var today = new Date(new Date().setHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);
my output like :
2018-03-20T18:30:00.000Z
I need to get date as it is but time 2018-03-20T00:00:00.000Z
When you create a new Date(), the time zone is that of the system. When you use toISOString(), the time is printed in UTC. This means that your code will print a different result when running on systems with different time zones (it prints 2018-03-20T23:00:00.000Z for me).
Instead of using setHours(), use setUTCHours().
var today = new Date(new Date().setUTCHours(0,0,0,0));
var todaynew = today.toISOString();
console.log(todaynew);

How the .getTime() can preserve the original date dd/MM/yyyy?

I have a trouble. I have an angular Javascript application that is storing the dates in mysql with milliseconds, but in some moments the date is interpreted with one more or less day. For example:
If the user selects in the date picker: 03/02/2017, the application is saving this (in milliseconds) as 02/02/2017 or 04/02/2017. I believe it is due to the timezone. This is the way I'm using to convert the date in milliseconds:
var temp = $("#datetimeField").val().split("/");
var newDatetime = new Date(temp[2], temp[1] - 1, temp[0]).getTime();
As you can see, I know the day, the month and the year before store it in the database. Normally the date is stored and works well, but in some moment the date changes as I showed above. How can I always get temp[2]/temp[1]-1/temp[0] ??? from the stored milliseconds?

How to detect day light saving and convert to BST (local time) in moment js

I am working on a project and suddenly found an issue. Issue was, server is sending Unix timestamps which is GMT but due to daylight saving the date
was populated as GMT. It can be achievable from server end but there is very simple way where we can convert it to local-time zone(in my case GMT to BST)
Create three variables
getPerfectLocalTime
yourUnixTimestamp
yourFormat
And below is the logic, you can use
var GMTtime = moment(yourUnixTimestamp*1000).format('YYYY-MM-DD HH:mm:ss'); // It should be YYYY-MM-DD format
var convertToUtc = moment.utc(GMTtime).format('YYYY-MM-DD HH:mm:ss');
var localTimeToDate = moment.utc(convertToUtc).toDate();
var isDSTDateTime = moment(GMTtime, 'YYYY-MM-DD');
var month = isDSTTime.format('M');
var day = isDSTTime.format('D');
var year = isDSTTime.format('YYYY');
if(moment([year, month, day]).isDST()){
getPerfectLocalTime = moment(localTimeToDate).format(yourFormat);
}else {
getPerfectLocalTime = moment(yourUnixTimestamp*1000).format(yourFormat);
}
Hope it helps anyone in programming world :)
Given that the only input in your example is yourUnixTimestamp, and you are multiplying by 1000, I'll assume that this is a traditional Unix Timestamp - an integer number in terms of whole seconds since midnight 1970-01-01 UTC.
Simply call moment.unix to parse this particular kind of input value. The resulting moment object will already be in local mode, so you can just format it directly.
moment.unix(yourUnixTimestamp).format(yourFormat)
If you want to know whether or not DST is in effect in the local time zone, you can just ask for that directly too.
moment.unix(yourUnixTimestamp).isDST()
But note that you do not need to know this to format the time correctly. Moment already takes this into consideration internally.

jQuery time difference of utc offSets

I want to find time difference between user's time and server side time. Like what time is user having on his system and what's the value coming from database. I have got it approximately.
But now my problem is what if user is from difference time zone rather then the value is coming from database? So now I want to find the exact difference by managing their time zones. Here I am putting my sample code and the values I am getting with their formats.
var studentSessionStartTimeDate = that._sessionData.studentSession.dtStart; //date with time from db
var splitTimeDate = studentSessionStartTimeDate.split(' ');
var oldDate = splitTimeDate[0]; // split date different
var dateold = new Date(oldDate).getTime(); //convert date into milliseconds
var time=that._sessionData.studentSession.start; // User's exact start time from db
var convertedTime=(Number(time.split(':')[0])*60+Number(time.split(':')[1]))*1000; // converted time in milliseconds
var sessionStartTime = dateold+convertedTime; // db time and date value in milliseconds
var systemTime = new Date().getTime(); // user's system time value in milliseconds
var timeDiff = sessionStartTime - systemTime; // now i want this time diff to be exact but it is not calculating the zone difference
Now if someone want I can get utc Offset from db also, but how can I get difference?
you could get browser time zone with following code:
new Date().getTimezoneOffset();

Client Time shown instead of server Time in javascript

I am into strange issue of javascript Date() function, these are the details
Server Side : Struts (ActionForm, Action class, jsp)
Client Side : jQuery, javascript
Now, I need a server time on the page and manipulate using javascript. So, I did Calendar.getInstance().getTimeinMillis(); in the action class and save it as an ActionForm attribute.
Now, at the client side, I got the long value (timeinMillis) from the styleId. But, to manipulate, when I do
var curTime = parseInt($("#serverTime").val());
var serverTime = new Date(curTime);
Now, the serverTime is providing client machine date and not server date though we are providing timeinMillis of server.
The strange part is when I pass string value of a date instead of long timeinMillis from server and pass it as an argument, it works well.
Any idea?
This is because your javascript runs on client machine, so when you create new Date() in javascript it picks up the client machine time.
Answer to second query if you pass the sever date as string it will create date object of that date.
Use below function
function calcTime(offset) {
// create Date object for current location
d = new Date();
// convert to msec, add local time zone offsetand get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object with supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The Server time is " + nd.toLocaleString();
}
Here you need to pass the offset of your server time with UTC
Finally resolved the issue with help of the above hints.
From java side, taken the offset from the UTC with the day light saving option.
so, in Action class
Calendar c = Calendar.getInstance();
TimeZone z = c.getTimeZone();
int offset = z.getOffset(c.getTimeInMillis());
This gives the offset of local timezone and UTC timezone including day light saving
At the javascript, I used,
var now = new Date();
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var sd = new Date(now_utc.getTime() + offset);
alert("The Server time is " + sd.toLocaleString());
And, this gives correct server time with the day light saving options.
Thanks a lot for your help, without them, would not be possible to work it out. Cheers!
A simple solution in PHP:
var phpDate = '<?php echo date('Y/m/d H:m:s');?>'
, serverDate = new Date(phpDate)
, month = serverDate.getMonth()+1 //getMonth() returns a 0-based number.
, day = serverDate.getDate()
, year = serverDate.getFullYear();
console.log(year + '-' + month + '-' + day);
If your server and client time are in different timezones and you want to show this difference to the user, then you have to send timezone information to the client as well.
Calendar.getInstance().getTimeinMillis() returns the number of milliseconds since the epoch, but it does not say anything about the timezone. It's just a number of milliseconds since midnight 1970/1/1 UTC and at any instant in time, this number is the same on any system (well, given the time is synced), regardless of system's timezone. This might give you the impression that you were getting client time instead of servers.
The reason why this works with string representation of date is the timezone information included in it, and Javascript's ability to parse that and take it into account when constructing the Date object.

Categories