How to use the tz function from moment-timezone

Find comprehensive JavaScript moment-timezone.tz code examples handpicked from public code repositorys.

moment-timezone.tz is a function that sets the timezone for a given Moment.js object or creates a new one with the given timezone.

239
240
241
242
243
244
245
246
247
248
249
250
}


// Get the offset value in Seconds for timezone


const getOffsetInSec = (value) => {
  const name = moment.tz.zone(value);
  if (name) {
    const x = moment().tz(value).format('Z');
    const split = x.split(':');
    const hour = Number(split[0]);
fork icon77
star icon54
watch icon20

+ 4 other calls in file

49
50
51
52
53
54
55
56
57
58
59
const xfarrapi = require('xfarr-api')
const { hentai } = require('./lib/scraper2.js')
let { msgFilter } = require('./lib/antispam')
const { mediafireDl } = require('./lib/mediafire.js')
const kaitime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const kaidate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
const time2 = moment().tz('Asia/Kolkata').format('HH:mm:ss')


        if(time2 < "23:59:00"){

fork icon623
star icon36
watch icon1

+ 2 other calls in file

How does moment-timezone.tz work?

moment-timezone.tz is a method provided by the Moment Timezone library in JavaScript that creates a new Moment object with a specific timezone, allowing users to work with and display dates and times in different time zones. It takes in a timezone name as an argument and returns a new Moment object with that timezone. If the timezone is not found, it will default to UTC. The timezone name can be in any of the formats supported by the IANA Time Zone Database.

75
76
77
78
79
80
81
82
83
84
const match = str.match(time_IANA_tz);
if (match) {
  const [hour, minute, second, tz] = match.slice(1);
  if (hour && minute && second && tz) {
    try {
      const t = moment.tz({ hour, minute, second }, tz);
      if (t.isValid()) {
        return t;
      }
      throw new Error('Invalid IANA format time. This is usually caused by an inappropriate format. Please check the input format.');
fork icon47
star icon20
watch icon5

181
182
183
184
185
186
187
188
189
190
    tz = tempStore.ipInfo.tz;
  }

  this.spoof.metadata['timezone'] = {
    locale: 'en-US',
    zone: moment.tz.zone(tz),
  };

  this.updateInjectionData(timezone);
}
fork icon44
star icon405
watch icon18

Ai Example

1
2
3
4
5
6
7
8
9
const moment = require("moment-timezone");

// Get the current date and time in UTC
const nowUTC = moment.utc();

// Convert it to a specific timezone
const nowLosAngeles = nowUTC.tz("America/Los_Angeles");

console.log(nowLosAngeles.format()); // output: 2022-11-06T23:30:45-08:00

In this example, we first create a moment object representing the current date and time in UTC using moment.utc(). We then use the tz method to convert this moment to the America/Los_Angeles timezone. Finally, we output the resulting moment in ISO-8601 format using the format method.

27
28
29
30
31
32
33
34
35
36
const Math_js = require('mathjs')
const fs = require('fs-extra')
const errorImg = 'https://i.imgur.com/VKoNMIR.png'
const errorImgg = 'https://i.ibb.co/jRCpLfn/user.png'
db.defaults({ group: [] }).write()
var tanggal = moment.tz('Asia/Jakarta').format('YYYY-MM-DD')

const {
    removeBackgroundFromImageBase64
} = require('remove.bg')
fork icon176
star icon145
watch icon8

106
107
108
109
110
111
112
113
114
115
    };
    break;
case 'date':
    obj.value = {
        '@type': 'Date',
        '@value': moment.tz(attr.value, 'Etc/UTC').format(moment.HTML5_FMT.DATE)
    };
    break;
case 'time':
    obj.value = {
fork icon74
star icon56
watch icon23

+ 11 other calls in file

605
606
607
608
609
610
611
612
613
614
		timeZone = this.creator && this.creator.get('timeZone');
		if (!timeZone) {
			timeZone = 'Etc/GMT';
		}
	}
	return MomentTimezone.tz(timeStamp, timeZone).format(format);
}

whiteSpaceToHtml (text) {
	return text
fork icon33
star icon58
watch icon12

+ 4 other calls in file

31
32
33
34
35
36
37
38
39
40
}
if(str.substring(10) === '99') {
  str = str.substring(0,10) + '00';
}
var dateFormat = 'YYYYMMDDHHmm';
var result = moment.tz(str, dateFormat, 'Europe/Copenhagen').tz('UTC');
if(result.isBefore(YEAR_1900)) {
  return null;
}
if(!result.isValid()){
fork icon7
star icon55
watch icon9

+ 23 other calls in file

32
33
34
35
36
37
38
39
40
41
        {
            errorMessage: "The timezone you passed is invalid.\n" +
            "You can find a list with the available time zones here:\n\n" +
            "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones (column `TZ`)",
            validate: val => {
                return !(typeof val !== 'string' || moment.tz.zone(val) === null);
            }
        }
    ]
}
fork icon124
star icon41
watch icon9

43
44
45
46
47
48
49
50
51
let speed = null
let track = null
let variation = null

const timestamp = utils.timestamp(parts[0], parts[8])
const age = moment.tz(timestamp, 'UTC').unix()

latitude = parts[2].trim().length > 0 && !isNaN(parts[2]) && "NS".includes(parts[3]) ? utils.coordinate(parts[2], parts[3]) : null
longitude = parts[4].trim().length > 0 && !isNaN(parts[4]) && "EW".includes(parts[5]) ? utils.coordinate(parts[4], parts[5]) : null
fork icon43
star icon25
watch icon16

+ 5 other calls in file

57
58
59
60
61
62
63
64
65
66
  style: thFontStyle,
  weight: thFontWeight,
});

const latestTimezoneData = require('moment-timezone/data/packed/latest.json');
moment.tz.load(latestTimezoneData);

const now = new Date();

await Promise.all(
fork icon28
star icon202
watch icon4

57
58
59
60
61
62
63
64
65
66
serverSide: true,
ajax: {
    url: href,
    type: 'POST',
    data: function (d) {
        d.clienttimezone = moment.tz.guess();
        d.clienttimezone = typeof d.clienttimezone == 'string' ? d.clienttimezone : "UTC";
        d.dateFrom = currDateRangeFrom;
        d.dateTo = currDateRangeTo;
    }
fork icon25
star icon89
watch icon13

99
100
101
102
103
104
105
106
107
108
let states = utils.tableParser(
    lines,
    {
        'date': {
            'idx': 2, 'mandatory': true, 'parser': elem => {
                return moment.tz(elem, 'YYYY-MM-DD HH:mm:ss', 'en', zone).format()
            }
        },
        'state': {'idx': 3, 'mandatory': true},
        'area': {'idx': 4, 'mandatory': false}
fork icon20
star icon50
watch icon9

82
83
84
85
86
87
88
89
90
91

let table = $('table.full-width tr').get(1).children.filter(e => e.type == 'tag')

let dayAndHours = table[2].children[0].data.trim() + ' ' + table[3].children[0].data.trim()
state = {
    date: moment.tz(dayAndHours, "YYYY/MM/DD HH:mm", zone).format()
}

if(table[4].children.length == 0) {
    state['status'] = 'Sem estado'
fork icon19
star icon50
watch icon9

+ 11 other calls in file

17
18
19
20
21
22
23
24
25
  if (event.start.date !== undefined) {
    return true;
  }

  return !(
    moment.tz(event.end.dateTime, 'YYYY-MM-DDTHH:mm:ss', event.end.timeZone).isAfter(now) &&
    moment.tz(event.start.dateTime, 'YYYY-MM-DDTHH:mm:ss', event.start.timeZone).isBefore(now)
  );
});
fork icon25
star icon34
watch icon9

+ 2 other calls in file

49
50
51
52
53
54
55
56
57
58
const setDefaultTimezone = (req, res) => {
    schoolTimezone = (res.locals.currentSchoolData || {}).timezone;
    userTimezone = getUserTimezone(req) || res.locals.currentTimezone;
    res.locals.currentTimezone = schoolTimezone || DEFAULT_TIMEZONE;

    moment.tz.setDefault(res.locals.currentTimezone);
    userHasSchoolTimezone = !schoolTimezone || res.locals.currentTimezone === userTimezone;

    res.locals.currentTimezoneOffset = getUtcOffset();
    res.locals.userTimezone = userTimezone;
fork icon12
star icon33
watch icon16

109
110
111
112
113
114
115
116
117
118
        if (options.via.type !== 'station') throw new Error('invalid or missing options.via type')
        options.via = options.via.id
}

const day = moment.tz(date, 'Europe/Berlin').format('DD.MM.YYYY')
const time = moment.tz(date, 'Europe/Berlin').format('HH:mm')

const body = {
        'results[5][5][function]': 'ws_find_connections',
        'results[5][5][data]': JSON.stringify([
fork icon6
star icon29
watch icon9

+ 7 other calls in file

96
97
98
99
100
101
102
103
104
105

eventMgr.formatted = function() {
  var resp = '*Upcoming Events!* _(Recurring events only shown once)_'

  this.events.forEach(function(event) {
    var dateStr = moment.tz(event.time, 'America/Chicago').format('ddd MM/DD hh:mma')
    var hosts = event.hosts.join(' & ')
    var location = event.location ? event.location : '_TBD_'
    resp += `
<${event.url}|${event.title}>
fork icon13
star icon10
watch icon12

+ 9 other calls in file

84
85
86
87
88
89
90
91
92
93
    // todo: bike
    // todo: withBestPrices?
}

const journeys = async (origin, destination, date, opt) => {
    date = moment.tz(new Date(date), 'Europe/Paris').format('YYYY-MM-DDTHH:mm:ss') // todo

    const params = {
        origin, // content doesn't matter, just has to be non-empty, originally contained the station name
        originCode: origin,
fork icon5
star icon22
watch icon5

44
45
46
47
48
49
50
51
52

let parsed;
if(format === 'fromNow') {
    parsed = moment(element).fromNow();
} else if(timezone && timezone !== '') {
    parsed = momentTz.tz(new Date(element), timezone).format(format);
} else {
    parsed = moment(new Date(element)).format(format);
}
fork icon1
star icon15
watch icon3