Convert string format Date(1528822800000) to date - javascript

I have a date format as follows:
var myDateString = "Date (1528822800000)"
I do not know what to call it with the name?
How can I convert it to date in javascript?
I tried using
Date (myDateString)
but the type that it returns is string rather than date.
I also tried
Date.parse (myDateString)
but it did not work.
How to convert Date (1528822800000) to date in javascript? (not use Moment.js)

This is Unix time :
From wiki :
Unix time passed 1,000,000,000 seconds in 2001-09-09T01:46:40Z. It was
celebrated in Copenhagen, Denmark at a party held by DKUUG (at
03:46:40 local time). Unix time (also known as POSIX time[citation
needed] or UNIX Epoch time1) is a system for describing a point in
time, defined as the number of seconds that have elapsed since
00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January
1970,[2].
var time = "Date (1528822800000)";
var unixtime = time.replace(/\D/g,'');
var date = new Date(Number(unixtime));
console.log(date);

It's called UNIX epoch time
You can convert it into Human date through this website
https://www.epochconverter.com/
For more information, you can read what is epoch time from that website too ("What is epoch time?")
Normally, the length is 10 if it is in seconds and 13 it is in milliseconds (*1000)
You can create date objects with new Date().
For example:
var d = new Date(milliseconds);

var myDateString = "Date (1528822800000)"
var time = myDateString.match(/([\d]+)/)
var date = new Date(parseInt(time[0]))
console.log(date.toISOString())
2018-06-12T17:00:00.000Z

Related

convert a string to date object javascript returns an incorrect date

I am trying to convert string to a date object in javascript, however what i day that is minus 1 from day in string. I don't know what is wrong. Here is the method
function formatDate(date_str)
{
console.log(date_str); //input : 2020-03-11
let new_date = new Date(date_str);
console.log(new_date); //output : Tue Mar 10 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
return new_date;
}
The most likely explanation is that parsing the input string "2020-03-11" with no other information equates it to a date of March 11, 2020 at midnight UTC. When you are in a different time zone, then it calculates your time zone offset and gives you a time four hours earlier which would be the day before in local time.
Why such behavior:
The date string(2020-03-11) did not specify any time zone, when you attempt to create a Date object with this string, JavaScript would assume the time zone to be UTC so the date is internally dealt with like as: 2020-03-11T00:00:00Z.
console.log(new_date) would internally call .toString() method on the new_date object and doing that would trigger a date conversion to your local time zone. From the question I believe you(the time on your machine actually) are in GMT-4, this is why 4 hrs is being subtracted from the output of the logs. More details about the date conversion due to time zone here
Possible Fix:
Firstly, we should understand that this is not a bug or an error, it is just how the JavaScript Date object works.
For the scenario described in your question, I'm guessing what you want is to avoid this time zone conversion on the date string. What you can do is add timezone information to the date string before using it to instantiate a date object, with this, javascript wouldn't assume that the date string you are passing into the Date() constructor is in UTC, and when you call Date.toString() or any other similar methods, there won't be any surprises. An implementation for this can be something like this:
// Sorry for the super long function name :)
function add_local_time_zone_to_date_string (date_string) {
// Getting your local time zone
let local_time_zone = (new Date().getTimezoneOffset() * -1) / 60;
// local_time_zone is a number, convert it to a string
local_time_zone = (local_time_zone.toString())
// Padding with 0s if needed to ensure it is of length 2
local_time_zone = local_time_zone.padStart(2, '0');
return `${date_string}T00:00:00+${local_time_zone}`
}
function formatDate(date_str) {
console.log(date_str); //input : 2020-03-11
const date_with_time_zone = add_local_time_zone_to_date_string(date_str);
let new_date = new Date(date_with_time_zone);
console.log(new_date); //output : There should be no surprises here
return new_date;
}

Convert utc date time to local date time using JavaScript or jQuery

I am storing a UTC date time in a SharePoint list and fetching it's value in c#, converting into milliseconds from 1 Jan 1970 and passing those milliseconds to JavaScript to get date object.
But when I create a date object, its value remains same as UTC date, I want that value to be in users local time zone and reflecting their daylight saving status.
You can use the TimezoneOffset in javascript, check the following code,
var d = new Date()
var n = d.getTimezoneOffset();
In this way you can calculate the time as you want.
Let me know if you need more details :)
When you create a new date in Javascript i assume you create it on the client side / client machine:
var d = new Date(millis);
The notion that the value remains the same in UTC no matter where you construct the Date object is correct, it's only a matter of how you display the date: in UTC or in the user's local timezone:
You can run this code to see the difference:
var local = date.toDateString() + ' ' + date.toTimeString();
var utc = date.toUTCString();
alert(local);
alert(utc);
Note that the value of millis is the milliseconds passed since 1970-01-01 00:00:00 UTC no matter where you are in this world. Calling new Date().getTime() on 2 opposite sides of the globe should return the same number of milliseconds.

JavaScript Date / Time

I have the following input and i can change the source of this data
Input
var strDate = "/Date(1391402871117+0100)/";
I can convert it to a date using eval, but i really dont want to eval
var DateResult1 = eval ("new Date(1391402871117+0100)");
console.log(DateResult1); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
I did try this, sadly do not work:
// Remove /Date( )/
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult3 = new Date(strDate);
console.log(DateResult3); //Date {Invalid Date}
When i write result of strDate i manual with out " it work.
var DateResult2 = new Date(1391402871117+0100);
console.log(DateResult2); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
How can convert the input data into a date with out using eval or any library?
You are very likely not getting a correct result out of this code:
var DateResult2 = new Date(1391402871117+0100);
The problem is the addition: 1391402871117+0100. 0100 is an octal constant, equal to 64 in decimal, which would add 64 milliseconds to the 1391402871117 timestamp. It seems likely to be indended as a time zone instead, but the Date constructor does not support time zones — only UTC and the local time zone of the browser.
Since UNIX timestamps are actually absolute (they are always in UTC), using just the timestamp would result in a Date instance referencing the correct instant in time, but possibly at another time zone. You can disregard the +0100 part, by converting the "1391402871117+0100" into an integer using parseInt:
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult2 = new Date(parseInt(strDate));
If you can change the data source, as you say, why not do this?
Have your data source generate something like this, to add the timezone offset to the timestamp:
// convert timezone offset hours into seconds and add them to the timestamp
return (unixTimestamp + (timezoneOffsetHours * 3600));
Then you can do something like this in your JS:
// Math.floor works faster than parseInt to convert a string to integer :)
var timestamp = Math.floor(result of above timestamp generation);
var DateResult = new Date(timestamp);
The reason:
new Date() can't handle timezones specified in this way (or at all as far as I can Google)
try by parsing string to int:
var strDate = "/Date(1391402871117+0100)/";
strDate = strDate.replace(/[^\d+]/g, '');
var DateResult3 = new Date(parseInt(strDate.split('+')[0]) + parseInt(strDate.split('+')[1]));
console.log(DateResult3);
Here is Demo

Convert Javascript Date object to PST time zone

I need to pick a future date from calender, suppose the date I am selecting is 10/14/2014, now what I want is to send the date with the time to server, so that at server end it always reaches as 6am time in PST timezone and the format of date should be UTC.
What I am doing is
targetDate = new Date($("#calendar").val());
targetDate = targetDate.toUTCString();
targetDate = targetDate.addHours(14);
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
The problem I am facing is that it is not letting me to add 14 hours since the object has already been converted to string.
addHours is the custom function I am having to add the hours in given time.
If I write
targetDate = new Date($("#calendar").val());
targetDate = targetDate.addHours(14);
targetDate = targetDate.toUTCString();
then it works good but in this case problem is time will always be different when the request is coming from different timezones.
Any help is appreciated.
This worked for me:
var myDate = new Date(1633071599000)
var pstDate = myDate.toLocaleString("en-US", {
timeZone: "America/Los_Angeles"
})
console.log(pstDate)
Which outputs "9/30/2021, 11:59:59 PM"
You said:
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
Uh - no. That will put you on the following day. If you wanted to stay in PST, you would subtract 8 hours from the UTC time. -8:00 means that it is 8 hours behind UTC.
However, the Pacific Time zone isn't just fixed at PST. It alternates between PST (-8) and PDT (-7) for daylight saving time. In order to determine the correct offset, you need to use a library that implements the TZDB database. Refer to this duplicate answer here.
The only way to do it without a fancy library is to actually be in the pacific time zone. JavaScript will convert UTC dates to the local time zone for display, and it will use the correct offset. But it only knows about the local time zone. If Pacific Time is not your local time zone, then you must use a library.
Suggest you look at DateJS http://code.google.com/p/datejs/ or http://www.datejs.com/. Handles PDT for you.
Here is an alternative for you:
Use: Date.UTC(year, month, day, hours, minutes, seconds, ms)
Example:
For 1 Jan 2013 6AM PST
var date = new Date(Date.UTC(2013, 0, 1, 14, 0, 0))
console.log(date.toUTCString());
Prints: "Tue, 01 Jan 2013 14:00:00 GMT"
var date = new Date();
var utcDate = new Date(date.toUTCString());
utcDate.setHours(utcDate.getHours()-8);
var usDate = new Date(utcDate);
console.log(usDate);
document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();
alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);
if(current_day==3 && hours >= 9 && hours <=11 )
if(hours!=11 && mins >= 45)
fbq('track', 'LT-Login');
}, false);
function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Here is the code that created to track fb pixel on Wednesdays between 9:45am PST and 11:00am PST
Mostly comment:
I need to pick a future date from calender, suppose the date I am
selecting is 10/14/2014,
Since there isn't a 14th month, I suppose you mean 14 October, 2014. Since this is an international forum, better to use an unambiguous format.
… and the format of date should be UTC
UTC is not a format, it's a standard time.
I think you are confused. If you want say 2014-10-14T06:00:00-08:00 in UTC, then the equivalent is 2014-10-14T14:00:00Z.
You are using the toUTCString method, but it is implementation dependent, so you'll get different results in different browsers. You probably want the toISOString method, but it's ES5 and not implemented in all browsers.
You need to provide some examples of how you want times to be converted, otherwise you may as well just get the date in ISO8601 format and append "T14:00:00Z" to it.
I think the question asks how to convert UTC to PST time (as indicated on the title). I'm making assumption that the local time is in pacific time (i.e. the server or local web browser etc)
if that's the case, in order to convert UTC time to local PST just do this
// Create date object from datetime (Assume this is the UTC /GMT) time
var date = new Date('Tue, 21 Apr 2020 09:20:30 GMT');
// Covert to local PST datetime, AGAIN this only works if the server/browser is in PST
date.toString();
I believe you can simply add 14 hours before converting to UTC.
Or you can create a new Date object out of the UTC string:
var date = new Date();
date = date.addHours(14);
var dateUTC = new Date(date.toUTCString());

why is javascript date an hour behind?

Hi I am trying to create a unix timestamp to represent the latest time of the current day (23:59:59) like so:
current_date = new Date();
end = new Date(current_date.getFullYear(), current_date.getMonth(), current_date.getDate(),23,59,59);
end = end.getTime() / 1000;
When I alert out the unix timestamp and convert it back into a datetime though it is an hour behind and represents 22:59:59 rather than 23:59:59.
I have to pass 24 to the date function for the hour parameter instead of 23 if I want 11pm is this right?
I am located in England so my time should be in GMT
new Date() will create the date in your timezone, whereas timestamps are in UTC. You appear to be in BST (GMT+1) hence the off-by-one error.
Instead, create a date and then use setUTCHours(23), setUTCMinutes(59) and setUTCSeconds(59) to get the correct timestamp.

Categories