Convert the epoch timestamp to time of 12:01 am - javascript

I'd like to get the Epoch timestamp of a date being entered by a user, but convert the time to 12:01 am in JavaScript.
How do I do that?

Take the timestamp and pass it while creating a instance of the Date class like:
let timestamp = 1629289414;
let dateInstance = new Date(timestamp * 1000);
console.log(dateInstance); // Wed Aug 18 2021 14:23:34....
From there on you have many ways to work with dateInstance. To get the 12:00am result from this it's more a string manipulation/adjusting thing.
Just check out the documentation on the the javascript Date instance: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
If you have further questions just post the code you've written and maybe I can help you out

Related

How can I convert GTM-0006 to ISO without Adding hours

I'm working in a from who has a date field and by default it shows the current date.
I set the date using this:
var date = new Date(); = Tue May 25 2021 17:06:01 GMT-0600 (Mountain Daylight Time) {}**
Everything works fine, but when I send the data to the controller, the JSON automatically converts it to ISO and the date received by the controller is 6 hours in advance.
I understand a little bit the context about GMT-0006 (my current timezone is 6 hours more than the 0 timezone), and the fact that my controllers received the date in ISO format because when I converted to ISO format is the same problem
date.toISOString() = "2021-05-25T23:06:01.861Z" (6 hours in advance)
so my question is, there is a way to create a date that allows me to use .toISOString() and keep the same?
or create a date with my current hour but -0000 so when I convert it to toISOString keeps the same?

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

Comparing date time with current datetime

From server I am getting a date time like this format "Thu, 02-Jan-2020 08:32:18 GMT" and I want to compare it current GMT date time . How I will do that in javascript.
const serverDate = new Date('Thu, 02-Jan-2020 08:32:18 GMT');
const clientDate = new Date();
const clientOffset = clientDate.getTimezoneOffset() * 60 * 1000; // get milliseconds from minutes
if (serverDate.getTime() > clientDate.getTime() + clientOffset) {
console.log('serverDate is later than clientDate');
} else {
console.log('serverDate is earlier than clientDate');
}
Here we are using built-in Date objects. getTime() method from this example is used to get the number of milliseconds passed since January 1st, 1970. This way we ended up just comparing 2 numbers.
If you set different timezone on a client device than GMT+0 on the server, getTimezoneOffset() comes to help. It returns the number of minutes we need to add to the getTime() result so that the client timestamp will also be in GMT+0 timezone.
I would suggest using moment.js. Using it is as simple as for example x.isSameAs(y), x.isBefore(y) x.isAfter(y)

Convert Normal Date to TimeStamp JavaScript

I have this date
Sep 7, 2019, 1:00 PM CEST
and want to convert it into a timestamp.
How would I go about doing this?
Replace CEST -> (CEST) and try to convert like below,
new Date("Sep 7, 2019, 1:00 PM CEST".replace('CEST', '(CEST)'))
Solution implemented based on this valuable article. Credit goes to article author :)
This answer is more of a pseudo-code then an exact javascript code.
The format of the string (posted by OP) is not supported natively. One of the answers used moment's moment function with second argument to parse the timezone i.e. CEST part in the querying string basically, but I found that conversion faulty too - https://www.epochconverter.com/timezones?q=1567841400&tz=Europe%2FBerlin - wondering what is 1567841400 try running this answer - https://stackoverflow.com/a/57830429/7986074
So the code would look like this -
Extract the time-zone attribute from the string - i.e. CEST - one may use ''.substr
Convert the extracted time-zone string to the UTC offset.
Use the UTC offset to make the date string.
Parse the string so made with utilities such as Date or moment
Did you try passing that string directly into the Date constructor? But before you have to get rid of the timezone. Here is an easy example:
// 1. A variable with your date as a string literal
const dateStr = "Sep 7, 2019, 1:00 PM CEST"
// 2. Get rid of the timezone and use the result to instantiate a new date
const d = new Date(dateStr.slice(0,-4))
// 3. Now that you have your date instance, use getTime() method to get the timestamp
const timestamp = d.getTime()
Hope my answer can help you!
You might need to convert your CEST to GMT+0200 which contains the timezone and the offset as well.
const date = new Date('Sep 7, 2019, 1:00 PM CEST'.replace('CEST', 'GMT+0200'));
console.log(date);

javascript date from php unix timestamp

In database i have a row with date & time, say 2014-04-16 00:00:00 then I convert that datetime to unix timestamp using
strtotime('2014-04-16 00:00:00') * 1000; // result 1397577600000
In javascript i am trying to get the hour using the following code
var d = new Date(1397577600000); // 1397577600000 from php unix timestamp in previous code
d.getHours(); // return 23
d.getMinutes(); // return 0
why getHours() return 23 instead of 0? is there any difference between js timestamp and php timestamp?
Date objects in javascript will always return values based on the browser's current timezone. So if d.getHours() is returning 23 for you, that would suggest your local browser timezone is one hour earlier than UTC (-01:00).
It you want the hours for a Date object based on UTC timezone, you can use:
d.getUTCHours()
Follow Up:
Just to throw out some free advice, you could use the following code to deal with your date values from one context to another:
PHP:
// Fetched from the db somehow
$datetime_db = '2014-04-16 00:00:00';
// Convert to PHP DateTime object:
$datetime_obj = new DateTime($datetime_db, new DateTimeZone('UTC'));
// Format DateTime object to javascript-friendly ISO-8601 format:
$datetime_iso = $datetime_obj->format(DateTime::W3C);
Javascript:
var d = new Date('2014-04-16T00:00:00+00:00'); // 2014-04-16T00:00:00+00:00 from PHP in previous code
d.getUTCHours(); // returns 0
This keeps the datetime variables in a language-specific object format when being handled in that language, and serializes the value into a string format that all current browsers/languages accept (the international standard ISO-8601).
I am getting 21 here because in Javascript local timezone of the user will be considered to fetch time and date.
Ok, based on what Arun P Johnny said.
I change the strtotime parameter to match my timezone, in this case i changed it to
strtotime('2014-04-16 00:00:00 GMT+7') * 1000;
hope this help anybody that have the same problem as I.

Categories