Hướng dẫn how to get local time in javascript - cách lấy giờ địa phương trong javascript

Chỉ cần phải giải quyết điều này nên tôi nghĩ rằng tôi sẽ để lại câu trả lời của mình. JQuery không bắt buộc tôi đã sử dụng để cập nhật phần tử vì tôi đã có bộ nhớ cache đối tượng.

Lần đầu tiên tôi đã viết một hàm PHP để trả về các ngày/thời gian cần thiết cho mẫu HTML của tôi

 /**
 * Gets the current location time based on timezone
 * @return string
 */


function get_the_local_time($timezone) {

    //$timezone ='Europe/London';

    $date = new DateTime('now', new DateTimeZone($timezone));

    return array(
        'local-machine-time' => $date->format('Y-m-d\TH:i:s+0000'),
        'local-time' => $date->format('h:i a')
    );

}

Điều này sau đó được sử dụng trong mẫu HTML của tôi để hiển thị thời gian ban đầu và hiển thị định dạng ngày theo yêu cầu của JavaScript trong thuộc tính dữ liệu.

        
            
        

Sau đó tôi đã sử dụng getSchours trên đối tượng ngày của mình để trả về thời gian bất kể thời gian của người dùng

Phương thức GetSchours () trả về giờ (từ 0 đến 23) của ngày và giờ được chỉ định, theo thời gian phổ quát.

var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};

Sau đó tôi sử dụng phương thức SetSeconds để cập nhật đối tượng ngày dựa trên số giây quá khứ vì tải trang (hàm khoảng cách đơn giản) và cập nhật HTML

Phương thức toLocaleTimeString() trả về một chuỗi với biểu diễn nhạy cảm với ngôn ngữ của phần thời gian của ngày. Trong các triển khai với hỗ trợ API Intl.DateTimeFormat, phương thức này chỉ cần gọi Intl.DateTimeFormat.toLocaleTimeString() method returns a string with a language-sensitive representation of the time portion of the date. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.

Thử nó

Cú pháp

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)

Thông số

Các đối số

        
            
        
0 và
        
            
        
1 tùy chỉnh hành vi của hàm và cho phép các ứng dụng chỉ định ngôn ngữ có quy ước định dạng nên được sử dụng.

Trong các triển khai hỗ trợ API Intl.DateTimeFormat, các tham số này tương ứng chính xác với các tham số của hàm tạo

        
            
        
3. Việc triển khai không có hỗ trợ Intl.DateTimeFormat được yêu cầu bỏ qua cả hai tham số, làm cho địa phương được sử dụng và hình thức của chuỗi được trả về hoàn toàn phụ thuộc vào thực hiện.

        
            
        
0 Tùy chọnOptional

Một chuỗi có thẻ ngôn ngữ BCP 47 hoặc một mảng các chuỗi đó. Tương ứng với tham số

        
            
        
0 của hàm tạo
        
            
        
3.

Trong các triển khai mà không cần hỗ trợ Intl.DateTimeFormat, tham số này bị bỏ qua và địa phương của máy chủ thường được sử dụng.

        
            
        
1 Tùy chọnOptional

Một đối tượng điều chỉnh định dạng đầu ra. Tương ứng với tham số

        
            
        
1 của hàm tạo
        
            
        
3. Nếu
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
2,
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
3,
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
4,
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
5 và
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
6 đều không được xác định, thì
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
3,
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
4,
var initClocks = function() {

    var $clocks = $('.box--location__time');

    function formatTime(hours, minutes) {

        if (hours === 0) {
            hours = 12;
        }

        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes < 10) {
            minutes = "0" + minutes;
        }

        return {
            hours: hours,
            minutes: minutes
        }
    }

    function displayTime(time, $clockDiv) {

        var currentTime = new Date(time);

        var hours = currentTime.getUTCHours();
        var minutes = currentTime.getUTCMinutes();
        var seconds = currentTime.getUTCSeconds();
        var initSeconds = seconds;

        var displayTime = formatTime(hours, minutes);

        $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        setInterval(function() {

            if (initSeconds > 60) {
                initSeconds = 1;
            } else {
                initSeconds++;
            }

            currentTime.setSeconds(initSeconds);

            hours = currentTime.getUTCHours();
            minutes = currentTime.getUTCMinutes();
            seconds = currentTime.getUTCSeconds();

            displayTime = formatTime(hours, minutes);

            $clockDiv.html(displayTime.hours + ":" + displayTime.minutes + ":" + seconds);

        }, 1000);

    }



    $clocks.each(function() {

        displayTime($(this).data('time'), $(this));

    });

};
5 sẽ được đặt thành
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
0.

Trong các triển khai mà không cần hỗ trợ Intl.DateTimeFormat, tham số này bị bỏ qua.

Xem hàm tạo

        
            
        
3 để biết chi tiết về các tham số này và cách sử dụng chúng.

Giá trị trả về

Một chuỗi đại diện cho phần thời gian của ví dụ

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
3 đã cho theo các quy ước cụ thể về ngôn ngữ.

Trong các triển khai với Intl.DateTimeFormat, điều này tương đương với

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
5, trong đó
        
            
        
1 đã được chuẩn hóa như mô tả ở trên.

Màn biểu diễn

Khi định dạng số lượng lớn ngày, tốt hơn là tạo một đối tượng Intl.DateTimeFormat và sử dụng phương thức

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
8 của nó.

Ví dụ

Sử dụng tolocaletimestring ()

Sử dụng cơ bản phương thức này mà không chỉ định

toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
9 trả về một chuỗi được định dạng trong ngôn ngữ mặc định và với các tùy chọn mặc định.

const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));

// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// → "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles

Sử dụng địa phương

Ví dụ này cho thấy một số biến thể trong các định dạng thời gian cục bộ. Để có được định dạng ngôn ngữ được sử dụng trong giao diện người dùng của ứng dụng của bạn, hãy đảm bảo chỉ định ngôn ngữ đó (và có thể là một số ngôn ngữ dự phòng) bằng đối số ____1010:

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US

// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('en-US'));
// → "7:00:00 PM"

// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString('en-GB'));
// → "03:00:00"

// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('ko-KR'));
// → "오후 12:00:00"

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString('ar-EG'));
// → "٧:٠٠:٠٠ م"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleTimeString(['ban', 'id']));
// → "11.00.00"

Sử dụng các tùy chọn

Các kết quả được cung cấp bởi toLocaleTimeString() có thể được tùy chỉnh bằng đối số

        
            
        
1:

const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// an application may want to use UTC and make that visible
const options = { timeZone: 'UTC', timeZoneName: 'short' };
console.log(date.toLocaleTimeString('en-US', options));
// → "3:00:00 AM GMT"

// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString('en-US', { hour12: false }));
// → "19:00:00"

// show only hours and minutes, use options with the default locale - use an empty array
console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// → "20:01"

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # sec-date.prototype.tolocaletimestring
# sec-date.prototype.tolocaletimestring
Thông số kỹ thuật API quốc tế hóa ECMAScript # Sup-date.prototype.tolocaletimestring
# sup-date.prototype.tolocaletimestring

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm

Giờ địa phương trong JavaScript là gì?

Thời gian địa phương được xác định bởi hệ thống trong câu hỏi chúng tôi thực hiện tệp của mình. Nút. JS sẽ được sử dụng như một thời gian chạy. Có hai cách tiếp cận cho vấn đề này được thảo luận dưới đây: Cách tiếp cận 1: Cách tiếp cận đầu tiên là sử dụng các phương pháp tích hợp được cung cấp bởi JavaScript.determined by the system in question where we execute our file. Node. js will be used as a runtime. There are two approaches to this problem that are discussed below: Approach 1: The first approach is to use the built-in methods provided by JavaScript.

Làm thế nào để tôi có được thời gian hệ thống địa phương?

Để lấy lại thời gian địa phương, hãy sử dụng hàm getlocaltime.GetLocalTime chuyển đổi thời gian hệ thống thành thời gian cục bộ dựa trên cài đặt vùng thời gian hiện tại và sao chép kết quả thành cấu trúc hệ thống.Bạn có thể đặt thời gian hệ thống bằng cách sử dụng hàm setlocaltime.use the GetLocalTime function. GetLocalTime converts the system time to a local time based on the current time-zone settings and copies the result to a SYSTEMTIME structure. You can set the system time by using the SetLocalTime function.

Làm cách nào để có được thời gian hiện tại trong JavaScript?

Trong JavaScript, chúng ta có thể dễ dàng nhận được ngày hoặc giờ hiện tại bằng cách sử dụng đối tượng ngày mới ().Theo mặc định, nó sử dụng múi giờ của trình duyệt của chúng tôi và hiển thị ngày dưới dạng chuỗi văn bản đầy đủ, chẳng hạn như "Thứ Sáu 17 tháng 6 năm 2022 10:54:59 GMT+0100 (Thời gian mùa hè của Anh)" có chứa ngày, thời gian và thời gian hiện tạivùng.using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.

GetTimezoneOffset trong JavaScript là gì?

GetTimeZoneOffset () Phương thức GetTimeZoneOffset () trả về sự khác biệt, tính theo phút, giữa một ngày được đánh giá trong múi giờ UTC và cùng ngày được đánh giá trong múi giờ địa phương.returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone.