How to convert time from JavaScript correctly in PHP? - javascript

I have a time array like
[2023,1,3,17,0,0]
When I use Date.UTC in javascript, It produces the right result
My code
const utcDate1 = new Date(Date.UTC(2023, 1, 3, 17,0,0));
console.log(utcDate1.toUTCString());
result:
"Fri, 03 Feb 2023 17:00:00 GMT"
How to get the same result in php like javascript?
I tried with mktime in php but the return result is not what i expected. It differs by one month.
my php code:
echo date("d-m-Y H:i:s", mktime(17,0,0,1,3,2023));
result by PHP :
03-01-2023 17:00:00

Javascript uses a date format that stores months 0 based: month "0" means January.
PHP does not, php considers January to be month 1.
Thats why in js Date.UTC(2023, 1, 3, 17,0,0) represents February 3rd, but in php mktime(17,0,0,1,3,2023) represents January 3rd.
When using that js-style date input [2023,1,3,17,0,0] in php you'll have to +1 to the month value.
If that part of your system is under your control and you have the possibility to change the format you use to exchange date values between js and php, i'd highly recommend to use a format that both systems understand. E.g. ISO 8601 or unix timestamps.

Related

How to resolve loss of minute precision formatting a moment in 12HR?

I've converted an ISO date string to a momentjs moment and then formatted that moment using .format("MM/DD/YYYY HH:MM").
When I output the final formatted moment, the minute value is incorrect as against the value read back from the iso string originally.
In this case the ISO string value holds 3:10 PM or "2016-08-03T03:10:00.000Z" as represented in the string. But when I call format the moment value is 4:07PM meaning three minutes have been subtracted during the format.
During debug I noted the following values at each assignment stage:
Step 1 (converting the db value to an ISO string):
var actualBCR_Local = moment.utc('#Model.Escalation.Actual_BCR_ISO').toISOString();
value: "2016-08-03T03:10:00.000Z"
Step 2 (converting the ISO string to a momentjs moment in order to represent the local time GMT+1):
var actualBCR_Local_Moment = moment(actualBCR_Local);
value: Wed Aug 03 2016 04:10:00 GMT+0100 (GMT Daylight Time)
Step 3 (formatting the moment in 12HR format for presentation, issue is here as I lose 3 minutes as against the original value which should be 04:10):
var actualBCR_Local_Formatted = actualBCR_Local_Moment.format("MM/DD/YYYY HH:MM");
value: "08/03/2016 04:08"
How can I prevent loss of minute precision when formatting a moment in 12HR format?
that's because you use the wrong format
In this section, you will find out that you are using HH:MM which means hour:month
If you use HH:mm then you will get correct time.
and that's why you got 2 minute loss, cause it display 08 as "month"
here is the what I tested

How to work with a Javascript +Date() numeric time stamp in Python?

I've a JavaScript date string which I want to convert in understandable form. E.g.
new Date(1415988000000)
which gives the output
Fri Nov 14 2014 23:30:00 GMT+0530 (IST)
I want to do this in python. I don't want to use PyV8. Is there any other alternative ?
You don't need to write Javascript in Python to convert the timestamps.
The following works in pure python.
Note:
The JS Date format is the number of milliseconds since Jan 1,1970 UTC.
Oddly enough, the python format for time.time() is the number of seconds since Jan 1, 1970 UTC.
This standard is sometimes called Unix time
First, for the milliseconds to seconds time conversion, you need to divide 1415988000000 by 1000, obtaining 1415988000
Then you can use the datetime library like this:
import datetime
d = datetime.datetime.fromtimestamp(1415988000)
print d
Obtaining:
2014-11-14 13:00:00
This print seems to have converted d to my TZ which is UTC-5.
So UTC time would be 18:00.
This explains the later time, 23:30, you receive in JS for the same stamp in IST or UTC+5:30

How to convert UTC time to normal time format using Moment js

I am trying to convert UTC time formate to local time format:
Here is the example:
I got the UTC format time from the server side, which looks like: 2014-09-17T11:09:58+1100. My requirement is to convert it to 17 Sep 2014.
However, I tried all the following method, but still get 03 Sep 2014. why this happened?
what I tried:
function dateFormatter(UTC) {
var dateFormat = 'd MMM YYYY';
console.log(moment(UTC).zone('+1100').format(dateFormat));
return moment(UTC).format(dateFormat).toLocaleString();
}
Those two method still get the same result: 03 Sep 2014
A few things:
UTC refers to Coordinated Universal Time, which is a system of timekeeping - not a format.
A value that is "in UTC" would have an offset of zero. Since you said the value has an offset of +1100, it doesn't make any sense to call it "UTC".
You should not call the zone function. That is for converting an input value to a particular time zone offset. Since your input value already contains an offset, calling it makes little sense.
If you're just trying to preserve the offset that you were given, then use moment.parseZone instead.
The format string characters are case sensitive. Lower-case d is for the day of the week as a number 0 through 6. You should use an upper-case D to specify the day of the month.
toLocaleString is not required. Note that you were calling that function from a string, not a date or a moment.
Putting it all together:
function dateFormatter(s) {
return moment.parseZone(s).format('D MMM YYYY');
}

Javascript shows the year 2014 instead of 2013 using php date string

I have a website and i want to display the PHP generated date through JavaScript and jQuery. The problem is, when i save the date string returned by PHP Date("d-m-Y H:i:s") function and pass this string to JavaScript new Date() function, it displays the next year rather than the current. For example, right now the year is 2013, but is shows 2014 instead. Below is my code to better explain my problem.
$(document).ready(function(){
var phpDateString = "<?php echo Date("d-m-Y H:i:s");?>"
alert(phpDateString); // Displays: 13-12-2013 01:49:17 (this is correct date)
var date = new Date(Date.parse(phpDateString));
alert(date); //Displays: Sun Jan 12 2014 01:53:20 (this is incorrect date)
});
I am using localhost Xampp Server and i have changed its timezone to date.timezone=Asia/Karachi in php.ini file. Why this is happening. Would be great if someone helps me out.
JavaScript is expecting MM-DD-YYYY but you are giving it DD-MM-YYYY. So it is turning 13 into 1 and thus you get January instead of December and an additional year being added. Because today is 12/12 it is a coincidence that the day is correct otherwise that would be wrong, too.

MySql TimeStamp and JavaScript Time

I have a time stamp in a MySQL database in GMT time [2013-07-19 10:12:56].
I know it should be in the DB as a DateTime and UTC but unfortunately this is the way it is.
I need to extract the timestamp and pass into JavaScript [HighCharts].
$time = strtotime('2013-07-19 10:12:56');
echo("Converting to UNIX Time: ");echo $time;
echo("Converting to JS Time: ");echo ($time*1000);
As JavaScript takes time in milliseconds hence the multiply buy 1000
Output: Converting to UNIX Time: 1374253976
Output: Converting to JS :Time: 1374253976000
The question I have is why does it come up in HighCharts as 17.12
When I put 1374253976000 into http://www.epochconverter.com I get:
GMT: Fri, 19 Jul 2013 17:12:56 GMT which is incorrect. The time should come up as displayed in the database as 10:12:56.
Any ideas why it would be 7h out ?
Epochtimeconverter says that Fri, 19 Jul 2013 10:12:56 GMT has following epoch times
Epoch timestamp: 1374228776
Timestamp in milliseconds: 1374228776000
Human time (GMT): Fri, 19 Jul 2013 10:12:56 GMT
Human time (your time zone): Friday, July 19, 2013 3:42:56 PM
Note, it's NOT 1374253976 as you are getting. So that is the problem, the conversion from epochtime to highcharts, etc. is correct. It's your epochtime that is coming to be wrong
PHP will treat the string to be in server's timezone, unless mentioned otherwise.
Give this a try, specify the timezone explicitly as GMT as follows
$time = strtotime('2013-07-19 10:12:56' . ' GMT');
echo("Converting to UNIX Time: ");echo $time;
echo("Converting to JS Time: ");echo ($time*1000);
The 7h difference that you were observing may be because your server is located in a the timezone -7 ?
Problem #1
The primary problem is in your conversion step using strtotime. PHP tries to guess the relationship of the time string to the time zone (probably using your time zone), but in your situation it needs to know more to guess properly. You can do that by explicitly telling PHP that the time string is represented as GMT (Greenwich Mean Time).
Since your database only has the form of YYYY-MM-DD HH:MM:SS, you can concatenate the necessary GMT identifier onto it during your strtotime invocation.
$time = strtotime('2013-07-19 10:12:56' . ' GMT');
For example:
<pre>
<?php
$time = strtotime('2013-07-19 10:12:56' . ' GMT');
echo("Converting to UNIX Time: $time\n");
echo("Converting to JS Time: ");
echo ($time*1000);
?>
</pre>
Converting to UNIX Time: 1374228776
Converting to JS Time: 1374228776000
Pasting the resulting UNIX Time into Epoch Converter results correctly in GMT: Fri, 19 Jul 2013 10:12:56 GMT
Problem #2
Changing your PHP code as above is necessary, but since it is not fully working for you, I can see that you have one more problem going on. (Sebastian tried to help you with this.)
What I would add to Sebastian's comments is that global settings need to be configured BEFORE you create any charts or chart objects in your JavaScript. Otherwise they will have no effect on the output of those charts. So you need to make sure that the following configuration is applied before any chart objects exist in your code.
Highcharts.setOptions({
global: {
useUTC: false
}
});
(If you don't use this configuration, your charts will still work fine, but dates and times will show relative to Greenwich Mean Time instead of the local time zone for each user viewing the charts.)
Discussion (placed afterwards for those who hate discussion don't have to read it):
I verified that if you are following the above suggested modification to your PHP code, then you now have the correct UTC/GMT numeric epoch time passed to JavaScript. You can confirm this 100% for sure with the following code:
Date.UTC(2013, 6, 19, 10, 12, 56)
1374228776000
new Date(1374228776000).toUTCString()
"Mon, 19 Aug 2013 10:12:56 GMT"
The second problem you are apparently facing is two-fold: making Highcharts properly interpret this as a UTC/GMT value rather than a value from some other (such as local) timezone, AND telling Highcharts to properly output the timezone in your desired format.
Making Highcharts properly interpret your time numbers: By default Highcharts assumes numeric time data like these are in UTC [[1331028000000, 5], [1331031600000, 6], [1331035200000, 4]]. Unless there is something strange lurking in your JavaScript and altering how the time data is processed, you should be good in that regard.
Making Highcharts display the correct time in the human-readable dates on your charts: this is where you should play close attention to the API here: http://api.highcharts.com/highcharts#global.useUTC
By the way, Sebastian Bochan is a member of the Highcharts support team, so you can certainly trust his comments.
You have a timezone issue. At GMT the time-stamp 2013-07-19 10:12:56 translates to 1374228776 seconds after epoch: http://jsfiddle.net/hsvtE/
Your PHP script however returns the incorrect unix time:
Output: Converting to UNIX Time: 1374253976
As you can see the difference between the two timestamps is:
1374253976 (incorrect)
-1374228776 (correct)
-----------
25200 seconds
The time your PHP script returns is 25200 seconds (or seven hours) ahead of GMT time. The reason PHP returns the wrong time is because of the way the strtotime function works.
If no timezone is specified in the time-stamp then strtotime assumes that the time-stamp belongs to the default timezone.
There are two methods to solve this problem:
Method 1: Set the default timezone to GMT
You can get and set the default timezone in PHP using the functions date_default_timezone_get and date_default_timezone_set. Using these two functions you could set the correct timezone for your timestamp as follows:
function get_time($timestamp, $timezone = 'GMT') {
$default_timezone = date_default_timezone_get(); // get current timezone
date_default_timezone_set($timezone); // set correct timezone
$time = strtotime($timestamp); // get correct time
date_default_timezone_set($default_timezone); // reset original timezone
return $time; // return correct time
}
Now you may safely get the correct time at GMT by simply calling get_time instead of strtotime:
$time = get_time('2013-07-19 10:12:56');
I recommend you use this method because if the time-stamp already specifies a timezone then strtotime simply ignores the default timezone and uses the specified timezone instead.
Method 2: Specify the timezone in the time-stamp itself
The second method is much shorter:
function get_time($timestamp, $timezone = 'GMT') {
return strtotime($timestamp . ' ' . $timezone);
}
$time = get_time('2013-07-19 10:12:56');
However I would recommend that you use the first method instead because it's safer. For example if you provided the timestamp 2013-07-19 10:12:56 EST then the above function would call strtotime with a string with two timezones - 2013-07-19 10:12:56 EST GMT.
Conclusion
This simple change should solve your problems. If you want the time in milliseconds then simply multiply the time by 1000:
$time = 1000 * get_time('2013-07-19 10:12:56');
I'm assuming that your client side code is correct. Hence if you still have problems then you should take a look at your JavaScript.
In fact it is not a JS problem. The trick resides in PHP and how "strtotime" does its conversion with regard to default timezone.
In your example, the timestamp is calculated as if you were in "America/Los_Angeles" timezone, so you you get 1374253976 seconds instead of 1374228776 with timezone "GMT". Since you're converting timestamp relatively to GMT timezone on epochconverter, a "mismatch" appears.
The data you store in MySQL is in GMT, the timezone of your PHP installation is "America/Los_Angeles". When you "strtotime", you interprete the data into MYSQL as not being GMT but America/Los_Angeles. That's why there are 7 hours between the two.
Here is a little script to better explain this :
date_default_timezone_set('GMT');
echo strtotime('2013-07-19 10:12:56', time() - 10) . "\n";
date_default_timezone_set('America/Los_Angeles');
echo strtotime('2013-07-19 10:12:56', time() - 10) . "\n";
will display :
1374228776 // from epochconverter : Fri, 19 Jul 2013 10:12:56 GMT
1374253976 // from epochconverter : Fri, 19 Jul 2013 17:12:56 GMT
Notice how the sequence "287" is replaced by the sequence "539".
In PHP, almost every function manipulating time will do so based on the currently defined timezone.
Look at this for more informations :
PHP Default TimeZone

Categories