Convert JSON date in PHP to Javascript - javascript

I'm new in Javascript, In PHP file I have script like so,
$JsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
$dateTime->format('U') = Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
$dateTime->format('O') = Difference to Greenwich time (GMT) in hours
which returns a data like this, and works fine.
/Date(1542798236000+0800)/
I tried to redo the code using javascript like so,
var dt = new Date();
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate()));
var newDate = '\/Date(' + newDate.getTime() + '+0800)\/';
But it returns like this
/Date(1542758400000+0800)/
In the API I want to access, it says "Login out of date" which means the datetime probably not correct.
Timezone: "Asia/Manila"
How do I manage to get the correct datetime.

Related

How do I compare a Date string in EST with a Date object in UTC?

I'm trying to compare this string 8/26/2019 6:53:13 which is in EST to a new Date() object to simply see if it's in the past. This works fine locally but on deployment heroku's new Date comes through in UTC format. So I had to do this hack
if(process.env.NODE_ENV){
timeSubmitted.setHours(timeSubmitted.getHours() + 5); // HACK but does work
}
I tried to get todays date and time in UTC format as an object not a string so I can compare it to other times in UTC format.
var date = new Date('2014-02-27T10:00:00')
//Thu Feb 27 2014 10:00:00 GMT-0500 (Eastern Standard Time) //this is an object
let d = moment.utc(new Date()).format()
//Does convert right now to a UTC time string, but then when I try convert it to an object
new Date(d)
//it goes back to EST
All together this does work, but isn't ideal because of the hardcoded number 5.
//SET DATE RANGE
const startDate = new Date();//This gets converted from EST to UTC
startDate.setMinutes(startDate.getMinutes() - 2); //Google spreadsheets saves minutes a little in the past
//startDate = new Date(startDate.getTime() + startDate.getTimezoneOffset() * 60000);
const endDate = new Date();
endDate.setDate(endDate.getDate() + 5)
console.log('startDate ' ,startDate,'endDate ',endDate)
rows.forEach(row=>{
//row.timestamp looks like this '8/26/2019 6:53:13' in EST
var date= row.timestamp.split(" ")[0].split('/')
var time=row.timestamp.split(" ")[1].split(':')
var timeSubmitted = new Date(date[2], date[0] - 1, date[1], time[0], time[1], time[2]); //So this is in EST
//but then when deploying to heroku i had to do this hack.
if(process.env.NODE_ENV){
timeSubmitted.setHours(timeSubmitted.getHours() + 5); // HACK -- It's the only way I could get this time to be in UTC/timeSubmitted = new Date(timeSubmitted.getTime() + timeSubmitted.getTimezoneOffset() * 60000);
}
console.log('timeSubmitted',typeof timeSubmitted, typeof startDate, timeSubmitted, startDate, timeSubmitted >= startDate, timeSubmitted < endDate)
if(timeSubmitted >= startDate && timeSubmitted < endDate){ //Within the date range so check if the names are in the roster
slackers = slackers.filter(function(a){return a.fullname !== row.whatsyourname})
}
})
messageSlackers(slackers, id)
Timezones are just a factor taken into consideration when generating a human-readable string from a date.
But a date is a point in time, regardless of timezones. Time doesn't know about timezones! Humans invented timezones.
You're probably stringising your Date objects in some manner that uses your local timezone by default (didn't show us this code). This doesn't matter.
Comparing two Dates works. Always. You don't have to worry about some hidden timezone component ruining it. Just compare your dates and you'll see that it works fine.
tl;dr: Dates are not in a "format". Dates are dates.

How to get utc date from timestamp using javascript?

I have a variable containing timestamp ( in seconds generated with php ), I used following code to create date object using javascript
var newdate = new Date(arrivalDate);
then used following code to get formated date in utc
var tempdate = newdate.getUTCFullYear()+'-'+('0' + (newdate.getUTCMonth()+1)).slice(-2)+'-'+('0' + newdate.getUTCDate()).slice(-2);
It returns me a 1 day before date, not sure how to get utc date from a timestamp.
var newdate = new Date(arrivalDate);
newdate.toUTCString();

Json utc time to local time

I discovered that this URL api-sunrise-sun sunset gives date time in UTC format however I want to convert on the fly to local time irrespective where my webpage is opened ! How would I achieve that?
I suppose you are showing the time after successfully getting the json. Try this:
//today's date, or whatever
var t_date = new Date().toLocaleDateString();
//time from json. example: 10:04:34 PM
var t_from_json = response["results"]["sunrise"]
var utc_date = new Date( t_date + " " + t_from_json + " UTC")
//Date 2017-02-21T22:04:34.000Z
//two options:
utc_date.toString();
//"Tue Feb 21 2017 19:04:34 GMT-0300 (CLST)"
var offset = new Date().getTimezoneOffset();
utc_date.setMinutes(utc_date.getMinutes() - offset);
//Date 2017-02-21T19:04:34.000Z

UTC Times in JavaScript

I am trying to get the current UTC date to store in my database. My local time is 9:11 p.m. This equates to 1:11 a.m. UTC. When I look in my database, I notice that 1:11 p.m. is getting written to. I'm confused. In order to get the UTC time in JavaScript, I'm using the following code:
var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);
What am I doing wrong?
A lttle searching turned out you can do this:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Even shorter:
var utcDate = new Date(new Date().toUTCString().substr(0, 25));
How do you convert a JavaScript date to UTC?
It is a commonly used way, instead of creating a ISO8601 string, to get date and time of UTC out. Because if you use a string, then you'll not be able to use every single native methods of Date(), and some people might use regex for that, which is slower than native ways.
But if you are storing it in some kind of database like localstorage, a ISO8601 string is recommended because it can also save timezone offsets, but in your case every date is turned into UTC, so timezone really does not matter.
If you want the UTC time of a local date object, use the UTC methods to get it. All javascript date objects are local dates.
var date = new Date(); // date object in local timezone
If you want the UTC time, you can try the implementation dependent toUTCString method:
var UTCstring = date.toUTCString();
but I wouldn't trust that. If you want an ISO8601 string (which most databases want) in UTC time then:
var isoDate = date.getUTCFullYear() + '-' +
addZ((date.getUTCMonth()) + 1) + '-' +
addZ(date.getUTCDate()) + 'T' +
addZ(date.getUTCHours()) + ':' +
addZ(date.getUTCMinutes()) + ':' +
addZ(date.getUTCSeconds()) + 'Z';
where the addZ function is:
function addZ(n) {
return (n<10? '0' : '') + n;
}
Modify to suit.
Edit
To adjust a local date object to display the same time as UTC, just add the timezone offset:
function adjustToUTC(d) {
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
return d;
}
alert(adjustToUTC(new Date())); // shows UTC time but will display local offset
Take care with the above. If you are say UTC+5hrs, then it will return a date object 5 hours earlier but still show "UTC+5"
A function to convert a UTC ISO8601 string to a local date object:
function fromUTCISOString(s) {
var b = s.split(/[-T:\.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
alert(fromUTCISOString('2012-05-21T14:32:12Z')); // local time displayed
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

What is wrong with this javascript date difference calculate function?

Any idea why this function doesn't work properly in Internet Explorer?
function days_between(check_in, check_out)
{
var oneDay = 24*60*60*1000;
var firstDate = new Date(check_in);
var secondDate = new Date(check_out);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return diffDays;
}
in internet explorer it shows NaN as result.
im calling this function in this date format
var check_in = "2012-02-09";
var check_out = "2012-02-12";
var range = days_between(check_in, check_out);
Regards
IE doesn't support Date.parse or passing "2012-02-09" (with ISO dates) to new Date, you need to parse it yourself and pass new Date( 2012, 1, 9 ) or use a Date.parse shim for ISO dates
The date format you're passing (yyyy-mm-dd) isn't supported by Date. See the note here that says it must be in a format parsable by parse. See here for acceptable parse formats: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
You have problem in creating the Date Object
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
(Taken from http://www.w3schools.com/js/js_obj_date.asp)
You are giving the date arguments in an incorrect format. You can expect javascript to support these formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
To fix your immediate problem, you can use replace() to format your arguments.
function days_between(check_in, check_out)
{
var firstDate = new Date(check_in.replace('-' , '/'));
var secondDate = new Date(check_out.replace('-' , '/'));
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / 86400000);
return diffDays;
}
And by the way, you can replace oneDay with a constant.

Categories