Gawdsed
Gawdsed

Reputation: 21

PHP Get local machine time (windows or linux)

I'm writing a php bot which people will be running, this bot requires accurate time in order to function correctly. I'm currently using a timestamp function as follows:

//return string of a timestamp
private function timestamp()
{
    $date = date_create();
    return "(" . $date->format('H:i:s') . ")";
}

Now, I understand that there is a function to set the timezone

http://php.net/manual/en/function.date-timezone-set.php

My issue is that I will have users, users who know very little if not anything about PHP to set the timezones. I can't rely on them to set their own timezones as it will create headaches with formatting and typos, at the very least, if we could set the timezones via numbers instead of locations, for example my timezone is -6...

date_default_timezone_set("-6");  

I have found functions of people who have tried to create a function in order to set the local machine's time, but their functions are either outdated or not working.

Is there a function or an alternative robust way to get the local time for either a linux and windows machine for php 5.0+.

Thanks again for your help.

EDIT: even localtime() returns a wrong time...

Upvotes: 2

Views: 2372

Answers (2)

Bhautik Nada
Bhautik Nada

Reputation: 387

You can current local time via below Javascript.

    <script>

        // For 24 hours    

        var ct = new Date();
        var hr = ct.getHours();
        var mt = ct.getMinutes();
        if (mt < 10) {
            mt = "0" + mt;
        }
        document.write("<b>" + hr + ":" + mt + " " + "</b>");    


        // For 12 hours (AM / PM)

        var ct = new Date();
        var hr = ct.getHours();
        var mt = ct.getMinutes();

        var ampm = "AM";

        if (hr >= 12) {
            ampm = "PM";
            hr = hr - 12;
        }
        if (hr == 0) {
            hr = 12;
        }
        if (mt < 10) {
            mt = "0" + mt;
        }

        document.write("<b>" + hr + ":" + mt + " " + ampm + "</b>");

   </script>

Upvotes: 0

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

You can either use the supported timezones or set one with other timezones like

date_default_timezone_set('Etc/GMT' . '-6');

Upvotes: 1

Related Questions