Utc時間跟Local時間的區別


utctime=localTime+localOffset; timeOffset is in minutes

 

 注意在C#中,ToLocalTime()?是不是根據服務器的時間,真正要換成客戶的時間,只能用timezoneoffset嗎?

客戶端timezoneoffset的獲取方法是: var offSet = new Date().getTimezoneOffset();

把這個傳到服務器里,用utctime-offSet就是客戶端的時間,注意offSet是根據分鍾數的。

 

UTC即世界標准時間,北京時間與UTC的時差為+8,也就是UTC+8=北京時間

一般保存在數據庫里是存UTC時間,然后在頁面再轉為LOCAL時間。

JS把UTC時間轉為LOCAL時間的方法如下:

   var localDate = new Date(utcDate.toString());

LOCAL時間跟UTC時間的區別代碼測試如下:

后端代碼:

using System;
using System.Web.Mvc;

namespace CloudCodeTest.Controllers
{
    public class TimeTestController : Controller
    {
        // GET: TimeTest
        public ActionResult Index()
        {
            DateTime utcTime = DateTime.UtcNow;
            DateTime localTime = DateTime.Now;
            // return View(utcTime);//好像不能直接這么寫,需要建立一個Model,如下:
            var model = new DateTimeTestModel
            {
                utcTime = utcTime,
                localTime = localTime
            };
            return View(model);

        }
    }

    public class DateTimeTestModel
    {
        public DateTime utcTime { get; set; }
        public DateTime localTime { get; set; }
    }
}

前端代碼:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

UTC 時間為: @Model.utcTime
<br />
本地時間為:@Model.localTime

測試結果如下:

 

 代碼目錄:C...CodeTest=>TimeTestController

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM