Object property looking different after printing on it's own - javascript

I am trying to use luxon to generate a new date using a timezone. This is my code:
var luxon = require('luxon');
luxon.Settings.defaultZoneName = 'UTC+4';
var date = luxon.DateTime.local();
console.log(date);
var now = new Date(date.ts);
console.log(now.toString());
And this is the console:
DateTime {
ts: 2018-09-13T13:09:45.333+04:00,
zone: UTC+4,
locale: en-US }
Thu Sep 13 2018 11:09:45 GMT+0200 (CEST)
But if I try to access the ts property like so
var date = luxon.DateTime.local();
console.log(date.ts); // here
var now = new Date(date.ts);
console.log(now.toString());
I get this in the console:
1536830052009
Thu Sep 13 2018 11:14:12 GMT+0200 (CEST)
Why is that? Is it doing some kind of math in the background? Also it turns out this date.ts is just ignoring my timezone. How can I fix that?

First 1536830052009, This is your time in milliseconds,
new Date(1536830052009)
// output Thu Sep 13 2018 11:14:12 GMT+0200 (CEST)
You may want to check your timezone with getTimezoneOffset()
Returns the time difference between UTC time and local time, in minutes
Many people use moment.js to play with Date, I know it is not in your question but maybe you could find some usefull things

ts is not a public property and you shouldn't use it. Luxon does all sorts of tricks under the covers to get the math right. If you want the timestamp, just use date.toMillis(). If you want a JS Date, use date.toJSDate().
Two other important things to know:
It's not ignoring your zone. The zone doesn't change the time. It's more like metadata about a time that affects how we display it. The Luxon docs cover this a bit. You shouldn't expect to extract a different timestamp by fiddling with the zone. Now is always now.
Remember that the native Date object doesn't support timezones other than your local one. So anytime you convert from a Luxon object to a native Date, that information is lost. The time itself will be the same (meaning, it will represent the same millisecond), but it will express it in the local time.

Related

Convert date from UK GMT string to local date in JavaScript

I have a situation where I am always returned the date from the server as a UK date time string.
E.g. '2020-07-19 16:40:00'
This would be 4:40PM in UK at +01:00, or 3:40PM UTC.
I want to be able to convert this time from GMT to the local time on the computer;
If I do this when in the UK...
var date = new Date('2020-06-19 16:40:00 GMT');
it returns Fri Jun 19 2020 17:40:00 GMT+0100 (British Summer Time)
Which is an hour out.
If I do the date in winter time (without daylight savings), this is correct.
var date = new Date('2020-01-19 16:40:00 GMT');
returns Sun Jan 19 2020 16:40:00 GMT+0000 (Greenwich Mean Time)
Is there a way I can correctly adjust this to always give the correct time regardless of what timezone the computer is set in, based on UK clock times.
Thanks in advance
As I understand your question, you don't know if the timestamp from the server is GMT or BST as the offset isn't included. You can work it out using plain JS but it's somewhat kludgy and error prone, see Calculate Timezone offset only for one particular timezone.
It would be much better to get the server to use an ISO 8601 format supported by ECMAScript and either send the offset or always use UTC/GMT.
If that isn't an option, you can use a library like Luxon to specify the location (and hence offset rules) to use for parsing, e.g.
let DateTime = luxon.DateTime;
['2020-07-19 16:40:00', // BST +1
'2020-01-19 16:40:00' // GMT +0
].forEach(ts => console.log(
DateTime.fromFormat(ts, 'yyyy-LL-dd HH:mm:ss', {zone: 'Europe/London'}))
);
<script src="https://cdn.jsdelivr.net/npm/luxon#1.24.1/build/global/luxon.min.js"></script>
PS Don't forget to always tell the parser the format to parse.

Why does Javascript show me the wrong date?

Consider the following date object which is created in JavaScript.
var date = new Date("2017-09-07T16:46:06.000Z");
This date object should be equivalent to Sep 7 2017 4:46:06 PM
However, in the browser console, when I type the following:
console.log(date);
The following is returned:
Fri Sep 08 2017 02:46:06 GMT+1000 (E. Australia Standard Time)
The time is wrong. (It actually is today's date, but the time is completely wrong).
Key points of confusion:
My computer timezone is set to GMT+1000 (Australia/Brisbane)
When I created the date object, I did not specify the timezone, therefore it should conform to my systems timezone
When I log the date object to the console, it is still using GMT+1000 (Australia/Brisbane) but the date is different
When you created the date, you did specify a timezone. That Z at the end means Zulu or Greenwich Mean Time. Your computer is 10 hours off from GMT, so it adjusts to your local timezone for display.
If you want the date to be in your local time zone, remove the Z
var date = new Date("2017-09-07T16:46:06.000Z");
So it looks like the Z at the end of your date string is meant to represent UTC or Zulu time
var date = new Date("2017-09-07T16:46:06.000");
should be the correct solution

JavaScript change timezone

Hello I am using Twitter REST API to call the home_timeline for timelines.
But I found that the object it returned had the created_at with GMT+0 timezone, how can I adjust the timezone to the user's local timezone for example GMT+8?
Here is the original data with GMT+0 from Twitter API:
Wed May 04 16:23:13 +0000 2016
what's the expected output format?
you can try:
var d = new Date('Wed May 04 16:23:13 +0000 2016');
var localeTime = d.toLocaleString();
console.log(localeTime);
if you expect a specific output format, you can use http://momentjs.com/timezone/ , to change both the timezone and format
I'm highly recommend to use MomentJS timezone library.
Furthermore, I'm recommend not to use GMT+8 label for time shifting, and use, for example, "Asia/Shanghai" instead. I would save hours to debug for you.
So, code barebone look like:
let moment = require("moment-timezone");
moment("Wed May 04 16:23:13 +0000 2016").tz("Asia/Shanghai").format('YYYYMMDD hh:mm:ss')
Output would be something like "20160505 12:23:13".
Thanks!

How to keep the Date as it is without being converted into local time zone?

I am having issue with the localtime zone things in javascript. If I got a string value from the server is "2014-02-03T00:00:00.000Z", once I pass it into Date object new Date('2014-02-03T00:00:00.000Z'), the new date object will be in localtime zone ex. Sun Feb 02 2014 18:00:00 GMT-0600 (CST). How to keep the value as 'Mon Feb 03 2014 00:00:00' ? I see a lot of people is using moment.js for dealing date, but I don't find any help with this issue.
Thanks
You can use getUTCDate() method. It will return you correct date.
http://jsbin.com/zizukapuba/1/edit?output
It will convert the date into required format with reference to system local timezone.
NOTE: If you use, the getISOString() method, then it will again make the changes with reference to your local time, that is, GMT -6.00.
The Date object stores your date as "2014-02-03T00:00:00.000Z".
When you display your Date object, the toString() function is used to get a string to display the date. toString() displays the date using the local time zone. Try using the toISOString() function or toUTCDateString().

How to update the date to the current date for UTC -8

I want to display a UTC date using this JavaScriptcode on my webpage.
<script>
function myDate()
{
var now = new Date();
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
var x = document.getElementById("demo");
x.innerHTML=d;
}
</script>
With this code I am getting UTC date displayed as a local string as follows: "Thu Jul 04 2013 00:00:00 GMT+0530 (India Standard Time)"
I do not want display the string with a local time offset (GMT+0530 (IST)), instead I want the time to appear as UTC string format
The date returned by different browser are of different format
to remove GMT OFFSET from date you can use replace
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
d = d.toString().replace(/GMT.+/,"");
Firstly, the problem is that you are instantiating a local Date object by passing in the UTC year, month and day. This then creates a local Date with the values provided. by doing this you might be creating an incorrect date based on whether you want it to be UTC or local. IN your case, if you want var now as UTC, the way you are currently instantiating is incorrect as its in local time.
Anyway, dates can be tricky in in JavaScript, so I would consider using Moment.js for this
It's a fantastic library that provides all of the functions for manipulating and converting JavaScript dates that you could ever need.
For example with moment you can just do the following:
var now = moment(); // current date and time in local format
var nowAsUTC = now.utc(); // current local date and time converted to UTC
var alsoNowAsUTC = moment.utc() // same as the line above, but staring in UTC
console.log(nowUTC.format("DD/MM/YYYY, hh:mm:ss"))// prints a pretty UTC string
Hmmm.. Are you sure you want to display UTC-8? I will take a guess that you are really wanting to convert the time to US Pacific time zone. That is not always UTC-8. Sometimes it is UTC-8, and sometimes it is UTC-7.
If you're not actually in the US Pacific Time zone, the only way to do this reliably in JavaScript is with a library that implements the TZDB database. I list several of them here.
For example, using walltime-js library, you can do the following:
var date = new Date();
var pacific = WallTime.UTCToWallTime(date, "America/Los_Angeles");
var s = pacific.toDateString() + ' ' + pacific.toFormattedTime();
// output: "Fri Apr 26 2013 5:44 PM"
You can't just add or subtract a fixed number, because the target time zone may use a different offset depending on exactly what date you're talking about. This is primarily due to Daylight Saving Time, but also because time zones have changed over time.

Categories

Resources