How to Use a Specific Gmt for a Function Which Will Be Recognised by Other Time Zones

How to use a specific GMT for a function which will be recognised by other time zones

You can use Calendar method func dateComponents(in timeZone: TimeZone, from date: Date) -> DateComponents and get the hour component at the desired timezone. Then you just need to check if it is contained in the desired hour range:

let timeZone = TimeZone(secondsFromGMT: 36000)!
let hourInAEST = Calendar.current.dateComponents(in: timeZone, from: Date()).hour!

if 9..<12 ~= hourInAEST {
print(true)
} else {
print(false)
}

GMT to local time conversion ERROR with swift UIKIT

The problem there is that you are getting the timezone offset for today. You need to get the timezone offset for the same date you are using:

let timeZone = TimeZone.current.secondsFromGMT(for: interval)
print("TIMEZONE IN HOURS: \(timeZone/3600)")

Error: Timezone gmt+0200 is not recognized

I solved this problem. I cannot find answer anywhere on the internet so I do it on my own. I added this two lines at the start of the for loop:

let date = new Date(Completation.adate);
date = date.toLocaleDateString() + " " + date.toLocaleTimeString();

and then changed db query to:

const ACC_Copy = `INSERT INTO public.cg_completationscondensed(
id_c, userlogin, barcode, quantity, adate)
VALUES ('`+idc+`', '`+ulogin+`', '`+Completation.barcode+`', '`+Completation.quantity+`', '`+date+`');`;

and now it works fine, finally!

BigQuery does not recognise timezones when parsing

I've used the basic code sample from the documentation in order to check tabledata.insertAll method which is relevant for Dataflow streaming to Bigquery functionality, simulating the similar approach for timestamps transformation.

from google.cloud import bigquery
import dateutil, pytz
import dateutil.parser as dt

# Construct a BigQuery client object.
client = bigquery.Client()

# TODO(developer): Set table_id to the ID of table to append to.
table_id = "your-project.your_dataset.your_table"

t1=dateutil.parser.isoparse('2021-10-20 10:37:24')
t2=str(t1.astimezone(pytz.timezone('Europe/Zurich')))

rows_to_insert = [
{u"t1": t2}
]

errors = client.insert_rows_json(table_id, rows_to_insert) # Make an API request.
if errors == []:
print("New rows have been added.")
print (t2)
else:
print("Encountered errors while inserting rows: {}".format(errors))

It executed properly retaining timezone Europe/Zurich.

New rows have been added. 2021-10-20 10:37:24+02:00

As long as Bigquery UI console saves timestamps in UTC format my test record was properly converted and inserted in the target table:

Sample Image

Hope this clarifies my efforts given in the comments.

Convert date to another timezone in JavaScript

Here is the one-liner:

function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}

// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)

// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17

// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

This code return me GMT offset.

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
Locale.getDefault());
Date currentLocalTime = calendar.getTime();
DateFormat date = new SimpleDateFormat("Z");
String localTime = date.format(currentLocalTime);

It returns the time zone offset like this: +0530

If we use SimpleDateFormat below

DateFormat date = new SimpleDateFormat("z",Locale.getDefault());
String localTime = date.format(currentLocalTime);

It returns the time zone offset like this: GMT+05:30

R Change from stardard UTC time zone to multiple local time zones

Multiple problems here:

  1. format (and other time-related functions) only takes a length-1 argument for tz;
  2. time zones recognized by R do not include the popular "CST", "PST", etc.

To fix the first, the use of Map or mapply will suffice.

The second requires a little more research, unfortunately. Zones like "PST" and such, though popular in at least the US if not other countries, are not valid time zone strings (ref: CCTZ, a C++ library for translating between time zones, says so). Neither are "GMT-7", et al, though the latter can be faked by prepending with Etc/, as in: "Etc/GMT-7". Or you can go with the alternatives of "America/New_York" or "US/Eastern".

df$time_zone <- c("US/Eastern", "US/Pacific", "US/Central", "US/Eastern")
df
# day time_zone
# 1 2018-12-06 15:40:29 US/Eastern
# 2 2018-12-06 15:25:28 US/Pacific
# 3 2018-12-06 15:25:28 US/Central
# 4 2018-12-06 14:09:09 US/Eastern
mapply(format, df$day, tz = "GMT")
# [1] "2018-12-06 15:40:29" "2018-12-06 15:25:28" "2018-12-06 15:25:28"
# [4] "2018-12-06 14:09:09"
mapply(format, df$day, tz = df$time_zone)
# [1] "2018-12-06 10:40:29" "2018-12-06 07:25:28" "2018-12-06 09:25:28"
# [4] "2018-12-06 09:09:09"

All of the immediately-recognizable formats for R's time zones are found in a 594-element vector:

str(OlsonNames())
# chr [1:592] "Africa/Abidjan" "Africa/Accra" "Africa/Addis_Ababa" ...
# - attr(*, "Version")= chr "2018e"
set.seed(2)
sample(OlsonNames(), size=8)
# [1] "America/El_Salvador" "Etc/GMT+8" "Atlantic/Madeira"
# [4] "America/Creston" "Pacific/Port_Moresby" "Pacific/Ponape"
# [7] "America/Atka" "GB-Eire"
grep("US/", OlsonNames(), value = TRUE)
# [1] "US/Alaska" "US/Aleutian" "US/Arizona"
# [4] "US/Central" "US/East-Indiana" "US/Eastern"
# [7] "US/Hawaii" "US/Indiana-Starke" "US/Michigan"
# [10] "US/Mountain" "US/Pacific" "US/Pacific-New"
# [13] "US/Samoa"

In this example, you'll see one of the alternatives you can use: "Etc/GMT+8". Notice that + is to the west of the prime meridian, so

mapply(format, df$day, tz = "US/Eastern")
# [1] "2018-12-06 10:40:29" "2018-12-06 10:25:28" "2018-12-06 10:25:28"
# [4] "2018-12-06 09:09:09"
mapply(format, df$day, tz = "Etc/GMT+5")
# [1] "2018-12-06 10:40:29" "2018-12-06 10:25:28" "2018-12-06 10:25:28"
# [4] "2018-12-06 09:09:09"

Caveat emptor: using "US/Eastern" should take into account daylight savings where appropriate; "Etc/GMT+5" does not, I believe.

Some Time Zones return IllegalArgumentException

Question 1:

Here is the relevant doc

Gets the default TimeZone of the Java virtual machine. If the cached
default TimeZone is available, its clone is returned. Otherwise, the
method takes the following steps to determine the default time zone.

  • Use the user.timezone property value as the default time zone ID if
    it's available.
  • Detect the platform time zone ID. The source of the
    platform time zone and ID mapping may vary with implementation.
  • Use
    GMT as the last resort if the given or detected time zone ID is
    unknown.

Questions 2 , 3 and 4:

The exception for EET is thrown when you use the deprecated new Date(myString) function. I am not sure about the internal working of this method. But why bother? It is deprecated for a reason.

If you want to create a date object from an input string. There are a ton of answers about this on StackOverflow already. You really don't need to use new Date(string) anyways. Here are two quick solutions to get what you want. I assume you want your date string to be formatted as java.util.Date would print it. If this is not accurate, use this link to create your own format.

1. Using java.util.Date (old and better to avoid):

SimpleDateFormat oldJavaDateFormat = new SimpleDateFormat("EEE LLL dd HH:mm:ss z yyyy");
TimeZone.setDefault(TimeZone.getTimeZone("EET"));

//Surround with try/catch or throw
Date eventDate = oldJavaDateFormat.parse(new Date().toString());
//or if you need a date from some given date string
oldJavaDateFormat.parse("Thu Jan 13 15:13:13 EET 2033");

Result:

Fri Mar 26 20:52:40 EET 2021

2. Using the new java.time (preferred):

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE LLL dd HH:mm:ss z yyyy");
ZonedDateTime eventDate = ZonedDateTime.parse(new Date().toString(), formatter).withZoneSameLocal(ZoneId.of("EET"));
//or directly from a string
eventDate = ZonedDateTime.parse("Thu Jan 13 15:13:13 EET 2033", formatter);

Result:

2021-03-26T20:52:40+02:00[EET]

or for the second case (given string):

2033-01-13T15:13:13+02:00[Europe/Bucharest]

EDIT:

Using the first solution above, one needs to be careful about timezones. Invoking parse() on a SimpleDateFormat object may not work as intended. You may lose timezone information.



Related Topics



Leave a reply



Submit