How to get utc date from timestamp using javascript? - 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();

Related

How to add today's time to any date object and getISOString?

I have a ngbDatePicker which helps me to pick a date. Then it returns an object like this:
{year:2020,month:12,day:03}
I'd like to get an ISOString of this date with today's time(current). So if time is 18:42 I should be able to get something like this:
2020-12-03T18:42:00.000Z
To do that I parsed object and made date firstly
(model is the object holds date like above)
var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
//then to add today's time I found solution below on the internet whcih didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2 .getTime() - (date2 .getTimezoneOffset() * 60000)).toISOString();
Here isoDateTime returns 2020-12-10T03:00:00.000Z which is not I want.
How to solve this?
Working stackblitz
Just take the time part of a Date object and combine it with this.model:
var date2 = new Date();
var date = new Date(this.model.year, this.model.month-1, this.model.day,
date2.getHours(), date2.getMinutes(), date2.getSeconds());
var isoDateTime = date.toISOString();
console.log(isoDateTime);
The month parameter is 0 based, so we have to substract 1 from the month.
Result (I chose Dec.1st 2020 in the Datepicker):
2020-12-01T19:22:42.000Z
Try on Stackblitz
You can create a single Date for the time and append it to values from the object:
function myISOString(obj) {
let z = n=>('0'+n).slice(-2);
return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}
let obj = {year:2020, month:12, day: 3};
console.log(myISOString(obj));
PS the use of leading zeros like 03 for numbers should be avoided as once upon a time that notation indicated octal values (but not any more), so 09 might be confusing.

Convert JSON date in PHP to 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.

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

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);

How to add 4 hours to a formated date/time

I've used Date Format 1.2.3 to format my time into yyyy-mm-dd hh:MM:ss and used it for a startTime variable. How can add 4 hours to the startTime string and use it for a new variable (endTime)?
You can try to parse it as Date, add 4 hours and then format it into text again.
var d = new Date(startTime);
d.setHours(d.getHours() + 4);
var endTime = // Format d variable as you like
Parse it as a date then add 4 to the hours
Here's an example with the date object
var today = new Date();
today.setHours(today.getHours() + 4);
Javascript will automatically update the day/month/year if required

Categories