2012-06-04 13 views
6

Tengo un usuario autenticado con una zona horaria determinada, p. "Berlín, GMT + 1". En aras de esta pregunta digamos que tengo esto en el ámbito global:¿Cuál es la mejor manera de manejar zonas horarias con Javascript

var timeZone = "Berlin"; 
var gmtDistance = 1; 

¿Cuál es la mejor solución para tener toda la JS relacionada con fechas comportarse en consecuencia, lo que significa que si se crea un nuevo objeto Date se tomará en cuenta la zona horaria.


pensé que sería bastante sencillo, pero no parecen encontrar la manera perfecta de hacer esto en Google/SO. Yo privilegiaría una respuesta que no necesita ninguna biblioteca externa.

Respuesta

0

¿Qué tal algo así?

http://www.onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/

var rightNow = new Date(); 
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0); 
var temp = jan1.toGMTString(); 
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1)); 
var std_time_offset = (jan1 - jan2)/(1000 * 60 * 60); 
+0

Gracias por la respuesta, pero no parece óptimo – marcgg

+0

FYI, el autor de la publicación recomienda utilizar https://bitbucket.org/pellepim/jstimezonedetect en su lugar – Denis

1

Mi preferencia es la de almacenar todas las fechas en el lado del servidor utilizando la hora UTC, y cuando estoy manejando datos que vienen de vuelta a través de llamadas AJAX, para crear un controlador global que hace algo de análisis.

El siguiente ejemplo le permite utilizar simplemente:

app.ajax({ 
    url: '/My/Post/Url', 
    data: { 
     MyProperty: 'MyValue' 
    }, 
    success: function (data, status, xhr) { 
     // Do stuff here... 
    }, 
    error: function (xhr, settings, error) { 
     // Do stuff here... 
    } 
}); 

Pero, pre-analiza todos los valores devueltos en elemento de "datos" del funcionamiento "éxito" mediante la fijación de fechas para la hora UTC a la zona horaria local. Tenga en cuenta que, después de hacer esto, si procesa los datos, tendrá que corregirlos antes de volver a enviarlos al servidor, o lo publicará con el desplazamiento.

var app = window.app = $.extend(true, {}, app, { 
    // Creating a namespace for my app which is safe across multiple files. 
    ajax: function (options) { 
     var defaultSettings = { 
      type: 'POST', 
      async: true 
     }; 

     // Capture the settings. 
     var settings = $.extend(true, {}, defaultSettings, options); 

     // Install our general handlers; 
     if (settings.success) { 
      settings.success = function (data, textStatus, jqXHR) { 
       app.OnPostSuccess(data, textStatus, jqXHR, options.success); 
      } 
     } else 
      settings.success = app.OnPostSuccess; 

     if (settings.error) { 
      settings.error = function (jqXHR, ajaxSettings, thrownError) { 
       app.OnPostError(event, jqXHR, ajaxSettings, thrownError, options.error); 
      } 
     } else 
      settings.error = app.OnPostError; 

     $.ajax(settings); 
    }, 
    OnPostSuccess: function (data, textStatus, jqXHR, fn_after) { 
     // Do my generalized success handling here. 

     // Fix Dates. 
     var fixedData = app.FixDate(data); 

     // Call any other handler that's been specified. 
     if (typeof fn_after === 'function') 
      fn_after(fixedData, textStatus, jqXHR); 
    }, 
    OnPostError: function (jqXHR, ajaxSettings, thrownError, fn_after) { 
     // Do my generalized error handling here. 

     // Call any other handler that's been specified. 
     if (typeof fn_after === 'function') 
      fn_after(jqXHR, ajaxSettings, thrownError); 
    }, 
    FixDate: function (obj) { 
     var fixed = obj; 

     if (typeof obj == 'string' && obj.indexOf('\/Date(') == 0) { 
      // Microsoft date "/Date(12345678)/" - convert to real date. 
      fixed = new Date(parseInt(fixed.substr(6, fixed.length - 8), 10)); 
     } 

     if (typeof fixed === 'object') { 
      if (fixed.getTimezoneOffset) { 
       // If the value is a date, apply timezone correction. 
       var now = new Date(); 
       var offset = now.getTimezoneOffset(); // # of minutes from GMT. 
       fixed = new Date(fixed.getTime() + offset * 60000); 
       // This updates the value based on the offset. 
      } else { 
       // Otherwise, update each of its properties. 
       // This fixes objects with dates for properties, recursively. 
       $.each(fixed, function (index, value) { 
        fixed[index] = app.FixDate(value); 
       }); 
      } 
     } 

     return fixed; 
    } 
}); 

Todo eso configurado para llegar a esto. Si ahora maneja cosas como las fechas dentro de OnPostSuccess, puede asegurarse de que estén siempre en el formato correcto y siempre en la zona horaria correcta.

si se utiliza o no los anteriores AJAX métodos, puede utilizar el método FixDate de la siguiente manera:

var MyObj = { 
    MyDate: "\/Date(12345678)\/" 
}; 

console.log('Before: ', MyObj.MyDate); 
MyObj = app.FixDate(MyObj); 
console.log('After: ', MyObj.MyDate); 

Para ver el ejemplo en acción, visita nuestra jsFiddle siguiente:

http://jsfiddle.net/TroyAlford/TBNVV/

Nota: esto también incluye los bits AJAX, pero no se utilizan en el ejemplo, solo que están completos.

0

quizá Dojo Toolkit le puede dar algunas ideas acerca de que [debido al hecho de que usted no desea una biblioteca externa;)]

Dojo Toolkit viene con una clase agradable para la fecha/hora-manejo y con plena soporte de localización, incluso con soporte de zona horaria. http://dojotoolkit.org/api/1.6/dojo/date

Cuestiones relacionadas