查找和使用用户';JavaScript中的s时区';s日期构造函数

查找和使用用户';JavaScript中的s时区';s日期构造函数,javascript,datetime,Javascript,Datetime,日期本身是通过PHP提供和格式化的。但是,如果用户没有登录,那么我不知道他们的时区偏移量是多少,这就是为什么我被迫使用JavaScript的原因 我怎样才能找到偏移量并应用它,同时仍然将其保存在一行代码中?对不起,伙计。约会很难 如果可能,让服务器格式化您的日期字符串,并通过网页或ajax响应或其他方式将其发送到浏览器 如果真的,真的,真的想用javascript在客户端上进行时区转换,那么必须将感兴趣的时区规则发送到客户端。如果您有一台Windows机器,下面是一个powershell脚本,它

日期本身是通过PHP提供和格式化的。但是,如果用户没有登录,那么我不知道他们的时区偏移量是多少,这就是为什么我被迫使用JavaScript的原因


我怎样才能找到偏移量并应用它,同时仍然将其保存在一行代码中?

对不起,伙计。约会很难

如果可能,让服务器格式化您的日期字符串,并通过网页或ajax响应或其他方式将其发送到浏览器

如果真的,真的,真的想用javascript在客户端上进行时区转换,那么必须将感兴趣的时区规则发送到客户端。如果您有一台Windows机器,下面是一个powershell脚本,它将生成一个带有时区规则的javascript文件和一个执行转换的函数。当我需要将日期从第三方web api转换为不同于浏览器时区的时区时,我使用了这个选项

只有在需要将日期对象放入除浏览器时区或utc以外的时区时,才应该使用这种方法。即使这样,您也可以考虑使用Web服务来为您格式化日期。
new Date('April 12, 2012 05:00:00 ').toLocaleString();
#将.Net TimeZoneInfo对象序列化为javascript文件。
添加类型-AssemblyName System.Web.Extensions;
$f=“timezoneinfo.js”;
$ser=新对象System.Web.Script.Serialization.JavaScriptSerializer;
$tzi=[System.TimeZoneInfo]::FindSystemTimeZoneById(“中央标准时间”);
#要保持文件大小合理,请排除此网站没有活动的时区信息。
$exclude=@(“阿富汗标准时间”,
“阿拉伯标准时间”,
“阿拉伯标准时间”,
“阿拉伯标准时间”,
“阿根廷标准时间”,
“大西洋标准时间”,
“澳大利亚中央标准时间”,
“澳大利亚东部标准时间”,
“阿塞拜疆标准时间”,
“亚速尔群岛标准时间”,
“孟加拉国标准时间”,
“佛得角标准时间”,
“高加索标准时间”,
“Cen.澳大利亚标准时间”,
“中美洲标准时间”,
“中亚标准时间”,
“巴西中部标准时间”,
“中欧标准时间”,
“中欧标准时间”,
“中太平洋标准时间”,
“中国标准时间”,
“日期行标准时间”,
“E.非洲标准时间”,
“E.澳大利亚标准时间”,
“E.欧洲标准时间”,
“E.南美洲标准时间”,
“埃及标准时间”,
“叶卡捷琳堡标准时间”,
“斐济标准时间”,
“FLE标准时间”,
“格鲁吉亚标准时间”,
“格陵兰标准时间”,
“格林威治标准时间”,
“夏威夷标准时间”,
“印度标准时间”,
“伊朗标准时间”,
“以色列标准时间”,
“约旦标准时间”,
“加里宁格勒标准时间”,
“堪察加半岛标准时间”,
“韩国标准时间”,
“马加丹标准时间”,
“毛里求斯标准时间”,
“大西洋中部标准时间”,
“中东标准时间”,
“蒙得维的亚标准时间”,
“摩洛哥标准时间”,
“缅甸标准时间”,
“中亚标准时间”,
“纳米比亚标准时间”,
“尼泊尔标准时间”,
“纽芬兰标准时间”,
“东北亚标准时间”,
“北亚标准时间”,
“太平洋标准时间”,
“巴基斯坦标准时间”,
“巴拉圭标准时间”,
“浪漫标准时间”,
“俄罗斯标准时间”,
“南非东部标准时间”,
“南太平洋标准时间”,
“南非西部标准时间”,
“萨摩亚标准时间”,
“东南亚标准时间”,
“新加坡标准时间”,
“斯里兰卡标准时间”,
“叙利亚标准时间”,
“台北标准时间”,
“塔斯马尼亚标准时间”,
“东京标准时间”,
“汤加标准时间”,
“土耳其标准时间”,
“乌兰巴托标准时间”,
“委内瑞拉标准时间”,
“海参崴标准时间”,
“西澳大利亚标准时间”,
“W.中部非洲标准时间”,
“W.欧洲标准时间”,
“西亚标准时间”,
“西太平洋标准时间”,
“雅库茨克标准时间”);
“/*此文件由工具生成*/”|输出文件$f;
“(函数(TimeZoneInfo,未定义){”out file$f-Append;
$first=$true;
“var infos={”| out文件$f-Append;
[System.TimeZoneInfo]::GetSystemTimeZones()|{
$exclude-notcontains$\ux.Id}|%{
#塞里兹里亚时区信息
$s1=$ser.Serialize($\ux);
#序列化调整规则。将MS Ajax日期转换为JS日期构造函数。
$s2=$ser.Serialize($\.GetAdjustmentRules())-替换“\`\\/Date\((?。+?)\)\\/\`)”,“新日期(`1)”;
#将调整规则添加到生成的JSON中。
$s3=$s1.Substring(0,$s1.Length-1)+”,AdjustmentRules:“+$s2+”}”;
#将项添加到关联JS数组。
$s3=“`”+$\.ID+“`”:“+$s3;
如果(!$first){
$s3=“,”+$s3;
$s3 |写主机;
}否则{
$first=$false;
}
#这里的代码很俗气。但是接下来的几个步骤将删除我们不关心的属性,以降低文件大小。
#删除字符串。
$s3=$s3-替换“`”(Id | DisplayName | StandardName | DaylightName)`):“`+?`(,)?,”;
#删除除TotalMinutes之外的所有TimeSpan属性。
$s3=$s3-替换“`”(滴答声|天|小时|毫秒|分钟|秒|总天|总小时|总毫秒)`:[-0-9.]+?,“,”;
$s3=$s3-替换“,”“总秒数”:(-)\d+“,”;
$s3 |输出文件$f-追加;
}
“};”|输出文件$f-Append;
#添加客户端函数来进行转换。这主要来自使用reflector和查看IsFixedDateRule的MSDN。
$s4=”
//此函数将日期转换为适当的小时数,以使其在给定时区ID中显示正确。
TimeZoneInfo.ConvertTime=函数(dt,tzid){
if(typeof(dt)==`“未定义”| | dt==null){return null;}
如果(typeof(tzid)==`undefined`“| | tzid==null | | tzid===```”){return dt;}
var tz=信息[tzid];
if(typeof(tz)==“undefined””{return dt;}
var clientOffset=dt.getTimezoneOffset();
var adj=null;
var j=tz.AdjustmentRules.length;
对于(变量i=0;i# Serialize .Net TimeZoneInfo objects to a javascript file.
Add-Type -AssemblyName System.Web.Extensions;
$f = "timezoneinfo.js";
$ser = new-object System.Web.Script.Serialization.JavaScriptSerializer;
$tzi = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time");

# To keep the file size reasonable, exclude timezoneinfos where this web site has no activity.
$exclude = @("Afghanistan Standard Time",
"Arab Standard Time",
"Arabian Standard Time",
"Arabic Standard Time",
"Argentina Standard Time",
"Atlantic Standard Time",
"AUS Central Standard Time",
"AUS Eastern Standard Time",
"Azerbaijan Standard Time",
"Azores Standard Time",
"Bangladesh Standard Time",
"Cape Verde Standard Time",
"Caucasus Standard Time",
"Cen. Australia Standard Time",
"Central America Standard Time",
"Central Asia Standard Time",
"Central Brazilian Standard Time",
"Central Europe Standard Time",
"Central European Standard Time",
"Central Pacific Standard Time",
"China Standard Time",
"Dateline Standard Time",
"E. Africa Standard Time",
"E. Australia Standard Time",
"E. Europe Standard Time",
"E. South America Standard Time",
"Egypt Standard Time",
"Ekaterinburg Standard Time",
"Fiji Standard Time",
"FLE Standard Time",
"Georgian Standard Time",
"Greenland Standard Time",
"Greenwich Standard Time",
"Hawaiian Standard Time",
"India Standard Time",
"Iran Standard Time",
"Israel Standard Time",
"Jordan Standard Time",
"Kaliningrad Standard Time",
"Kamchatka Standard Time",
"Korea Standard Time",
"Magadan Standard Time",
"Mauritius Standard Time",
"Mid-Atlantic Standard Time",
"Middle East Standard Time",
"Montevideo Standard Time",
"Morocco Standard Time",
"Myanmar Standard Time",
"N. Central Asia Standard Time",
"Namibia Standard Time",
"Nepal Standard Time",
"Newfoundland Standard Time",
"North Asia East Standard Time",
"North Asia Standard Time",
"Pacific SA Standard Time",
"Pakistan Standard Time",
"Paraguay Standard Time",
"Romance Standard Time",
"Russian Standard Time",
"SA Eastern Standard Time",
"SA Pacific Standard Time",
"SA Western Standard Time",
"Samoa Standard Time",
"SE Asia Standard Time",
"Singapore Standard Time",
"Sri Lanka Standard Time",
"Syria Standard Time",
"Taipei Standard Time",
"Tasmania Standard Time",
"Tokyo Standard Time",
"Tonga Standard Time",
"Turkey Standard Time",
"Ulaanbaatar Standard Time",
"Venezuela Standard Time",
"Vladivostok Standard Time",
"W. Australia Standard Time",
"W. Central Africa Standard Time",
"W. Europe Standard Time",
"West Asia Standard Time",
"West Pacific Standard Time",
"Yakutsk Standard Time");

"/*This file was generated by a tool*/" | out-file $f;
"(function (TimeZoneInfo, undefined) {" | out-file $f -Append;

$first = $true;
"var infos = {" | out-file $f -Append;
[System.TimeZoneInfo]::GetSystemTimeZones() | ? {
    $exclude -notcontains $_.Id} | % {

    # Serizliae the TimeZoneInfo
    $s1 = $ser.Serialize($_);
    # Serialize the adjustment rules.  Convert MS Ajax dates into JS date constructors.
    $s2 = $ser.Serialize($_.GetAdjustmentRules()) -replace "\`"\\/Date\((?<ticks>.+?)\)\\/\`"", "new Date(`$1)";
    # Add the adjustment rules to the resulting JSON.
    $s3 = $s1.Substring(0, $s1.Length - 1) + ",AdjustmentRules:" + $s2 + "}";
    # Add item to associative JS array.
    $s3 = "`"" + $_.ID + "`":" + $s3;
    if (!$first) {      
        $s3 = "," + $s3;
        $s3 | write-host;
    } else {
        $first = $false;        
    }

    # Cheesy code here.  But the next few steps remove properties we don't care about to get keep the file size down.
    # Remove strings.
    $s3 = $s3 -replace "`"(Id|DisplayName|StandardName|DaylightName)`":`".+?`"(,)?", "";
    # Remove all of the TimeSpan properties except TotalMinutes.
    $s3 = $s3 -replace "`"(Ticks|Days|Hours|Milliseconds|Minutes|Seconds|TotalDays|TotalHours|TotalMilliseconds)`":[-0-9.]+?,", "";
    $s3 = $s3 -replace ",`"TotalSeconds`":(-)?\d+", "";

    $s3 | out-file $f -Append;
}
"};" | out-file $f -Append;


# Add the client function to do the conversion.  This mainly comes from using reflector and looking as MSDN for IsFixedDateRule.
$s4 = "
// This function will shift a date the approprate number of hours to make it appear correct for the given timezoneid.
TimeZoneInfo.ConvertTime = function(dt, tzid) {
    if (typeof(dt) === `"undefined`" || dt == null) { return null; }
    if (typeof(tzid) === `"undefined`" || tzid == null || tzid === `"`") { return dt; }
    var tz = infos[tzid];
    if (typeof(tz) === `"undefined`") { return dt; }

    var clientOffset = dt.getTimezoneOffset();

    var adj = null;
    var j = tz.AdjustmentRules.length;  
    for (var i = 0; i < j; i++) {
        if (tz.AdjustmentRules[i].DateStart <= dt) {
            if (tz.AdjustmentRules[i].DateEnd >= dt) {
                adj = tz.AdjustmentRules[i];
                break;
            }
        } 
    }

    function GetDaysInMonth(y, m)
    {
        return 32 - new Date(y, m, 32).getDate();
    }

    function GetTransitionDayOfMonth(t, y) {
        var startOfWeek = t.Week * 7 - 6;
        var firstDayOfWeek = new Date(y, t.Month - 1, 1).getDay();
        var transitionDay = null;
        var changeDayOfWeek = t.DayOfWeek;
        if (firstDayOfWeek <= changeDayOfWeek) {
            transitionDay = startOfWeek + (changeDayOfWeek - firstDayOfWeek);
        } else {
            transitionDay = startOfWeek + (7 - firstDayOfWeek + changeDayOfWeek);
        }
        if (transitionDay > GetDaysInMonth(y, t.Month - 1)) {
            transitionDay -= 7;
        }
        return transitionDay;
    }

    var dstOffset = 0;
    if (adj != null) {
        var dstStart = adj.DaylightTransitionStart.IsFixedDateRule ?
            new Date(dt.getFullYear(), adj.DaylightTransitionStart.Month - 1, adj.DaylightTransitionStart.Day, adj.DaylightTransitionStart.TimeOfDay.getHours()) :
            new Date(dt.getFullYear(), adj.DaylightTransitionStart.Month - 1, GetTransitionDayOfMonth(adj.DaylightTransitionStart, dt.getFullYear()), adj.DaylightTransitionStart.TimeOfDay.getHours());
        var dstEnd = adj.DaylightTransitionEnd.IsFixedDateRule ?
            new Date(dt.getFullYear(), adj.DaylightTransitionEnd.Month - 1, adj.DaylightTransitionEnd.Day, adj.DaylightTransitionEnd.TimeOfDay.getHours()) :
            new Date(dt.getFullYear(), adj.DaylightTransitionEnd.Month - 1, GetTransitionDayOfMonth(adj.DaylightTransitionEnd, dt.getFullYear()), adj.DaylightTransitionEnd.TimeOfDay.getHours());
        if (dstStart <= dt && dstEnd >= dt) {
            dstOffset = adj.DaylightDelta.TotalMinutes;
        }
    }
    var dtcopy = new Date(dt.getTime());
    dtcopy.setMinutes(dtcopy.getMinutes() + clientOffset + tz.BaseUtcOffset.TotalMinutes + dstOffset);
    return dtcopy;  
};
TimeZoneInfo.Get = function(tzid) { return infos[tzid]; };
";


$s4 | out-file $f -Append;


"} (window.TimeZoneInfo = window.TimeZoneInfo || {}));" | out-file $f -Append;

#//TimeZoneInfo.ConvertTime(new Date(2011,7,1,16,45), "Central Standard Time");
#//TimeZoneInfo.ConvertTime(new Date(2011,7,1,16,45), "Eastern Standard Time");
#//TimeZoneInfo.ConvertTime(new Date(2011,7,1,16,45), "South Africa Standard Time");
#notepad.exe $f;
d = new Date(); d.setTime(the_time_value);