How to show a Unix-time in a local time format

2019-08-11 03:43发布

问题:

I have a php variable say $expTime (which has a unixtime say-1359683953) . I want to display this variable on the client side(in a proper time format according to his local time) . I am so confused between the UTC ,GMT , DST all that things. Can anyone suggest a solution for this using php or javascript please.

when I am using echo date('h:i M d/y',$expTime) it is showing me a wrong time.

How I am saving the time to database:
var exp_day= parseInt($("#exp_day").val());
var exp_hrs= parseInt($("#exp_hrs").val());
var exp_min= parseInt($("#exp_min").val());
var exp_time = (exp_day*24*60*60) + (exp_hrs*60*60) + (exp_min*60) ;
then I posted the exp_time using ajax to a php file -
$expTime = time() + $_POST["exp_time"];

What I am retrieving from the database is $expTime . This $expTime I want to display it on the all the clients system according to there local time zone (also by making sure the day light saving)

回答1:

UNIX time values are usually UTC seconds since epoch. Javascript time values are UTC milliseconds since the same epoch. The ECMA-262 Date.prototype.toString method automatically generates a string representing the local time and takes account of daylight saving if it applies.

You can also use Date methods to create your own formatted string, they also return local time and date values. There are also UTC methods if you want to work in UTC.

To do this on the client, just provide a UTC time value from the server and then all you need in javascript is:

var timeValue = 1359683953;  // assume seconds
var date = new Date(timeValue * 1000);  // convert time value to milliseconds

alert(date); //  Fri 01 Feb 2013 11:59:13 GMT+1000 


回答2:

Use DateTime with timezones:

$datetime = new DateTime('@1359683953');
echo $datetime->format('h:i M d/y') . "<br>";
$datetime->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $datetime->format('h:i M d/y');

See it in action