Moment: Eliminar la zona horaria de un objeto moment.js

Creado en 4 dic. 2015  ·  3Comentarios  ·  Fuente: moment/moment

Estoy usando datetimepicker.js y su función date devuelve un objeto moment.js . Lo hace con el desplazamiento UTC local y mi fecha original tiene un desplazamiento diferente.

Mi fecha original:

2015-10-01T15:00:00.000Z

Lo que muestro en el selector de fecha y hora ( DD-MM HH:mm ):

01-10 15:00

Lo que consigo:

2015-10-01T15:40:00+01:00

Lo que quiero:

2015-10-01T15:40:00+00:00

Tenga en cuenta cómo eliminé el desplazamiento +01 al final.

¿Cómo puedo hacer esto aplicándolo para cualquier UTC local? Esto es, sin tener que eliminar manualmente el 01 (ya que puede ser cualquier otro desplazamiento local según la ubicación del usuario).

Esto es lo que tengo hasta ahora para obtener la fecha, pero no sé cómo eliminar el desplazamiento manteniendo la misma hora.

    var momentDate = timePicker.data("DateTimePicker").date();
    console.log(momentDate.format());
    //this prints  2015-10-01T15:40:00+01:00

Comentario más útil

const tmp = moment(valueAsDate).utc(true) - eso es lo que necesita eso ignora la zona horaria
entonces puede usar, por ejemplo, como tmp.toISOString() .

Todos 3 comentarios

Como momento, se formateará la fecha original para que sea una fecha de zona horaria local. es decir, 2017-08-02 10:00:00+02:00 tendrá el formato 2017-08-02 16:00:00+08:00 si el sistema de la máquina usa la zona horaria +08:00.

Escribí una función para formatear la fecha original ignorando la zona horaria:

/**
 * <strong i="7">@desc</strong> use moment to format a datetime
 * <strong i="8">@param</strong> string|date|timestamp datetime: the datetime to format
   the given datetime can have timezone, and the timezone will be kept in the process of output datetime
   i.e. formate('2017-09-08 11:24:00+08:00', 'D/M/YYYY HH:mm:ss Z') =>  8/9/2017 11:24:00 +08:00, as you see, +08:00 is kept, which is different from moment default behavior
   if timezone has not been given, local timezone will be used.
 * <strong i="9">@param</strong> string formatter: the target format you want to get
 * <strong i="10">@param</strong> string givenFormatter: moment allow developer to define your own formatter, i.e. DD/MM/YYYY HH,mm,ss which is not a statndard time format
 * <strong i="11">@return</strong> string new formatted datetime string
 * <strong i="12">@example</strong>:
   1. format(new Date(), 'YYYY-MM-DD HH:mm:ss')
   2. format(your_date, 'YYYY-MM-DD HH:mm:ss', 'DD/MM/YYYY HH,mm,ss')
 */
export function format(datetime, formatter, givenFormatter) {
  let localTimezoneOffset = timezoneOffset()
  let givenTimezoneOffset = moment.parseZone(datetime).utcOffset()

  if (givenTimezoneOffset !== 0) {
    return moment(datetime, givenFormatter).utcOffset(givenTimezoneOffset).format(formatter)
  }
  else {
    // big problem: we do not know whether timezone has not been given or it is +00:00
    // if its utc time is the same with itself, it means timezone has been given
    let u = utc(datetime, 'YYYY-MM-DD HH:mm:ss')
    let t = moment(datetime).parseZone(datetime).format('YYYY-MM-DD HH:mm:ss')
    if (u === t) {
      return moment(datetime, givenFormatter).utc().format(formatter)
    }
    else {
      return moment(datetime).format(formatter)
    }
  }
}

Código fuente: https://github.com/tangshuang/moment-format

Utilice esta función para dar formato a la fecha e ignorar la lógica de formato predeterminada del momento. 2017-08-02 10:00:00+02:00 tendrá el formato 2017/08/02 10:00:00+02:00.

const tmp = moment(valueAsDate).utc(true) - eso es lo que necesita eso ignora la zona horaria
entonces puede usar, por ejemplo, como tmp.toISOString() .

¿Fue útil esta página
0 / 5 - 0 calificaciones