跳至主要內容

9日


9日

获取\转换时区

方式一:调用API

TimeAPI

官网地址:https://www.timeapi.io/open in new window

API地址:https://timeapi.io/swagger/index.htmlopen in new window

以下是获取 Asia/Shanghai 时区的当前信息

https://timeapi.io/api/Time/current/zone?timeZone=Asia/Shanghai

返回结果为

{
    "year": 2024,
    "month": 4,
    "day": 9,
    "hour": 9,
    "minute": 52,
    "seconds": 54,
    "milliSeconds": 454,
    "dateTime": "2024-04-09T09:52:54.4541743",
    "date": "04/09/2024",
    "time": "09:52",
    "timeZone": "Asia/Shanghai",
    "dayOfWeek": "Tuesday",
    "dstActive": false
}

方式二:通过本时区计算出其他时区

TimeZoneInfo

.NET Framework 的 System中有时区转换的方法,文档地址:https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo?view=net-8.0#methodsopen in new window

以下是基于 本时区时间 转为 其他时区 的例子

using UnityEngine;
using System;

public class TimezoneConverter : MonoBehaviour
{
    void Start()
    {
        // 获取当前的本地时间
        DateTime localTime = DateTime.Now;

        // 打印本地时间
        Debug.Log("Local Time: " + localTime.ToString());

        // 获取系统支持的所有时区
        TimeZoneInfo[] timeZones = TimeZoneInfo.GetSystemTimeZones();

        foreach (TimeZoneInfo timeZone in timeZones)
        {
            // 将本地时间转换为指定时区的时间
            DateTime convertedTime = TimeZoneInfo.ConvertTime(localTime, TimeZoneInfo.Local, timeZone);

            // 打印转换后的时间和时区信息
            Debug.Log(timeZone.DisplayName + ": " + convertedTime.ToString());
        }
    }
}

SpaceTime

基于JS,地址:https://github.com/spencermountain/spacetimeopen in new window

以下是用 gotoAmerica/New_York 转为 America/Los_Angeles 的例子

var d = spacetime('March 1 2012', 'America/New_York')
//set the time
d = d.time('4:20pm')

d = d.goto('America/Los_Angeles')
d.time()
//'1:20pm'

Moment

基于JS,地址:https://github.com/moment/moment-timezoneopen in new window

以下使用 tz 进行时区转换的例子

var june = moment("2014-06-01T12:00:00Z");
june.tz('America/Los_Angeles').format('ha z'); // 5am PDT
june.tz('America/New_York').format('ha z');    // 8am EDT
june.tz('Asia/Tokyo').format('ha z');          // 9pm JST
june.tz('Australia/Sydney').format('ha z');    // 10pm EST

var dec = moment("2014-12-01T12:00:00Z");
dec.tz('America/Los_Angeles').format('ha z');  // 4am PST
dec.tz('America/New_York').format('ha z');     // 7am EST
dec.tz('Asia/Tokyo').format('ha z');           // 9pm JST
dec.tz('Australia/Sydney').format('ha z');     // 11pm EST
上次编辑于:
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度