How to identify timezone by string time and convert multiple timezones to one timezone in kotlin - kotlin

I have list of records with dateTime in different timezones
[
{
"id": 1,
"dateTime": "2023-01-01T14:10:24.478Z"
},
{
"id": 2,
"dateTime": "2023-01-22T08:39:48.374+08:00"
}.
{
"id": 3,
"dateTime": "2023-01-22T08:39:48.374+05:30"
}
]
data class Record(val id: Int, val dateTime: String)
I need to convert these all dateTime to my timezone (Eg: +04:00)
Is there a best way to identify timezone by dateTime value to convert it to my timezone? or do we need substring dateTime and find timezone value add custom method to get timezone?
Eg:
fun String.timezone() : String? {
return when(this) {
"+05:30" -> "Asia/Calcutta"
"Z" -> "UTC"
.....
else -> null
}
}
(I know how to convert dateTime to my tomezone if know tomezone of dateTime)

Are you asking how to map an offset to a time zone? You cannot. At any moment, several time zones can coincidentally share the same offset.
You said:
my timezone (Eg: +04:00)
Correction… Your example +04:00 is an offset from UTC, not a time zone.
An offset is merely a number of hours-minutes-seconds ahead or behind the temporal prime meridian of UTC. In Java, use ZoneOffset with OffsetDateTime.
A time zone is a named history of the past, present, and future changes to the offset used by the people of a particular region, as decided by their politicians. In Java, use ZoneId with ZonedDateTime.
Point on timeline
Offset from UTC
ZoneOffset
OffsetDateTime
Time zone
ZoneId
ZonedDateTime
A time zone has a name in the format of Continent/Region. For example, Africa/Casablanca or Pacific/Auckland. FYI, the time zone Asia/Calcutta has been renamed Asia/Kolkata.
Parse your inputs as OffsetDateTime objects.
(Java syntax; I don’t know Kotlin)
OffsetDateTime odt = OffsetDateTime.parse( "2023-01-22T08:39:48.374+08:00" ) ;
Apply your desired time zone.
ZoneId z = ZoneId.of( "Asia/Dubai" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

Related

BigQuery Timestamp in Select giving different format

using BigQuery query API to retrieve data from BigQuery. for timestamp column , am getting values in different format.
query="select * from table"
QueryJobConfiguration queryConfig = QueryJobConfiguration
.newBuilder(query)
.setUseLegacySql(false)
.build();
Value in Table : "2022-02-25 08:47:48.801665"
Value in Output : 1.645778868801665E9
If I am casting to string the getting proper value. why is this happening ?
can someone explain ?
You need to convert to TIMESTAMP, because it takes milliseconds since 1970-01-01T00:00:00 UTC. That's why you are getting this result.
You can convert this result to TIMESTAMP using this formula timestamp.toInstant().toEpochMilli() * 1000.
You can see this example:
QueryParameterValue.timestamp(
// Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
timestamp.toInstant().toEpochMilli() * 1000))
Here is more documentation about it.
If you want to cast from BigQuery. You have some options.
CAST the TIMESTAMP columns.
SELECT CAST(DATE("2022-02-25 08:47:48.801665") AS TIMESTAMP )
CAST TIMESTAMP to STRING.
SELECT STRING(TIMESTAMP "2022-02-25 08:47:48.801665", "UTC") AS string;
Give some format.
SELECT FORMAT_TIMESTAMP("%c", TIMESTAMP "2022-02-25 08:47:48.801665", "UTC") AS formatted;
You can see more documentation about CAST.

How to convert unix timestamp into Date

I am trying to convert Unix time stamp into date
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final String startdate = Instant.ofEpochSecond(Long.parseLong(requestVO.getStartDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
final String enddate = Instant.ofEpochSecond(Long.parseLong(requestVO.getEndDate().toString()))
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
above is what I have tried for the format of date Mentioned in DateTimeFormatter and requestVO.getStartDate() is giving Date type value.I am applying the startDate and endDate in sql query Like below
and ceo.erx_date between '"+startdate+"' and '"+enddate+"'
No compilation errors getting But, giving number format exception.
If requestVo.getStartDate() returns a Date object, your error is here:
Long.parseLong(requestVo.getStartDate())
As the documentation says, Long.parseLong(String) throws
NumberFormatException - if the string does not contain a parsable long.
Try this:
Long.parseLong(requestVo.getStartDate().getTime())
In every case two things:
Take care from NullPointerException: check if your date is null or not
Use preparedStatement and not string concatenation when write e query in Java
There are at least two reasons to use PreparedStatement instead of Statement:
They are faster then simple Statement: because Statement are compiled and execute every time, but PreparedStatment are compiled once
In case of PreparedStatement you are safe from the point of view of SQL injection
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is the legacy way to represent a moment in UTC.
.toInstant() // `Instant` is modern way to represent a moment in UTC.
.atZone( // Adjust from UTC to some time zone.
ZoneId.of( "America/Martinique" ) // Specify the time zone you had in mind for an offset of four hours behind UTC.
) // Returns a `ZonedDateTime` object.
.format( // Generate text representing the value of our `ZonedDateTime` object's content.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // A predefined formatter per ISO 8601 that omits any indication of time zone or offset-from-UTC.
)
.replace(
"T" , // Standard ISO 8601 formats use a `T` between the date and time-of-day portions.
" "
) // Returns a `String`.
java.util.Date::toInstant
requestVO.getStartDate() is giving Date type value.
You are working too hard.
Convert the terrible Date class object to its modern replacement, Instant. Notice how the legacy classes were given new methods for conversion to/from the modern java.time classes. Look for to… & from… methods on the old classes. In this case, Date::toInstant.
Instant instant = myJavaUtilDate.toInstant() ;
Zone versus offset
.atZone(ZoneId.of("GMT-4"))
Nope, -4 is not a time zone. That is an offset.
An offset-from-UTC is merely a number of hours-minutes-seconds ahead or behind the prime meridian.
A time zone is much more. A time zone is a history of the past, present, and future changes in offset used by the people of a particular region. A time zone carries a name in format of Continent/Region such as Asia/Kolkata or Pacific/Auckland.
Better to use a time zone than a mere offset. For one thing, you may be wrong about the offset. By using an time zone, java.time will determine the offset in effect at your intended moment.
Zone for offset of four hours behind UTC
Perhaps by -4 you have in mind a time zone such as America/Martinique, America/Aruba, or America/Puerto_Rico.
ZoneId z = ZoneId.of( "America/Puerto_Rico" ) ;
Instant + ZoneId ➡ ZonedDateTime
Apply that ZoneId to produce a ZonedDateTime object. Same moment, different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Generating text
Produce a string in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
String output = zdt.toString() ;
But you wanted a format similar to ISO 8601, but without the T in the middle and with no indicator of offset/zone. I do not recommend reporting a moment without representing the time zone or offset. But if you insist:
String output =
zdt
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;

Datetime issue in odoo10?

in my custom model I defined the fields
time_from = fields.Datetime(string="Time From", default=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
time_to = fields.Datetime(string="Time To", default=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
tot_time = fields.Char("Time Difference", compute='_get_time')
this is my compute function
#api.depends('time_from', 'time_to')
def _get_time(self):
t1 = datetime.datetime.strptime(self.time_from, '%Y-%m-%d %H:%M:%S')
t2 = datetime.datetime.strptime(self.time_to, '%Y-%m-%d %H:%M:%S')
if t2<t1:
raise ValidationError('Time To must greater than Time From')
time_diff = (t2-t1)
self.tot_time = time_diff
This is success fully prints time difference.
Time from and time to are mm/dd/yyyy hh:mm:ss format.
How to change this to mm/dd/yyyy hh:mm:ss format
I changed the format like this '%Y-%d-%m %H:%M:%S' .
but it is not getting correct result.
How to change the format?
is it possible to calculate time difference in this format?
The Date and Datetime are saved as strings in the database in a certain format (see the class definition on fields.py. You cannot change the format that is used for the fields in the ORM. If you want to change the format of the date or datetime when you show these fields you can do it not from the code but from:
1) Settings -> Translations -> Find your language and inside you can change the way the fields Date and Datetime are rendered on the client side.
2) If you have a template/report you can use for example<p t-esc="formatLang(time.strftime('%Y-%m-%d %H:%M:%S')" /> or another expression you want to change how the date or datetime will be formed.
3) In the field definition in your xml files you can use custom javascript/widget that will do the rendering.

How to create a Date variable in Elm

I want to hardcode a date in a record in elm. The record signature is
type alias Record = { .., startDate : Date, .. }
On my code I am doing
record = { .., startDate = Date.fromString "2011/1/1", .. }
The problem is that the Record type expects a Date type but Date.fromString signature is
String -> Result.Result String Date.Date
How can I create the Date to use on the Record type?
You're getting the Result because there is a chance that parsing the string to a date failed. You can handle it one of 2 ways.
Ignore it
If you want to just say "I know this string will be valid date and I'm not worried that I may have messed it up" then you can just provide a default date
Date.fromString "2011/1/1" |> Result.withDefault (Date.fromTime 0)
This will leave you with a Date but will default to the unix epoch if the parse fails.
Use it
Think about what you would want to happen if the parse were to fail and handle it where the date is used. Ex. if you're displaying it as a string you could display the date or if the parse failed display "TBA".
Note: You may have noticed that Date.fromTime just returns a Date not a Result (because an Int can always be parsed to a Date). If you don't mind converting your dates to unix timestamps you could hardcode the timestamp and use that without having to deal with Results

Convert Local Time to UTC in SQL Server 2005 [duplicate]

We are dealing with an application that needs to handle global time data from different time zones and daylight savings time settings. The idea is to store everything in UTC format internally and only convert back and forth for the localized user interfaces. Does the SQL Server offer any mechanisms for dealing with the translations given a time, a country and a timezone?
This must be a common problem, so I'm surprised google wouldn't turn up anything usable.
Any pointers?
This works for dates that currently have the same UTC offset as SQL Server's host; it doesn't account for daylight savings changes. Replace YOUR_DATE with the local date to convert.
SELECT DATEADD(second, DATEDIFF(second, GETDATE(), GETUTCDATE()), YOUR_DATE);
7 years passed and...
actually there's this new SQL Server 2016 feature that does exactly what you need.
It is called AT TIME ZONE and it converts date to a specified time zone considering DST (daylight saving time) changes.
More info here:
https://msdn.microsoft.com/en-us/library/mt612795.aspx
While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.
That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.
Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.
Here is the code to convert one zone DateTime to another zone DateTime
DECLARE #UTCDateTime DATETIME = GETUTCDATE();
DECLARE #ConvertedZoneDateTime DATETIME;
-- 'UTC' to 'India Standard Time' DATETIME
SET #ConvertedZoneDateTime = #UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time'
SELECT #UTCDateTime AS UTCDATE,#ConvertedZoneDateTime AS IndiaStandardTime
-- 'India Standard Time' to 'UTC' DATETIME
SET #UTCDateTime = #ConvertedZoneDateTime AT TIME ZONE 'India Standard Time' AT TIME ZONE 'UTC'
SELECT #ConvertedZoneDateTime AS IndiaStandardTime,#UTCDateTime AS UTCDATE
Note: AT TIME ZONE works only on SQL Server 2016+ and the advantage is that it automatically considers Daylight when converting to a particular Time zone
For SQL Server 2016 and newer, and Azure SQL Database, use the built in AT TIME ZONE statement.
For older editions of SQL Server, you can use my SQL Server Time Zone Support project to convert between IANA standard time zones, as listed here.
UTC to Local is like this:
SELECT Tzdb.UtcToLocal('2015-07-01 00:00:00', 'America/Los_Angeles')
Local to UTC is like this:
SELECT Tzdb.LocalToUtc('2015-07-01 00:00:00', 'America/Los_Angeles', 1, 1)
The numeric options are flag for controlling the behavior when the local time values are affected by daylight saving time. These are described in detail in the project's documentation.
SQL Server 2008 has a type called datetimeoffset. It's really useful for this type of stuff.
http://msdn.microsoft.com/en-us/library/bb630289.aspx
Then you can use the function SWITCHOFFSET to move it from one timezone to another, but still keeping the same UTC value.
http://msdn.microsoft.com/en-us/library/bb677244.aspx
Rob
I tend to lean towards using DateTimeOffset for all date-time storage that isn't related to a local event (ie: meeting/party, etc, 12pm-3pm at the museum).
To get the current DTO as UTC:
DECLARE #utcNow DATETIMEOFFSET = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
DECLARE #utcToday DATE = CONVERT(DATE, #utcNow);
DECLARE #utcTomorrow DATE = DATEADD(D, 1, #utcNow);
SELECT #utcToday [today]
,#utcTomorrow [tomorrow]
,#utcNow [utcNow]
NOTE: I will always use UTC when sending over the wire... client-side JS can easily get to/from local UTC. See: new Date().toJSON() ...
The following JS will handle parsing a UTC/GMT date in ISO8601 format to a local datetime.
if (typeof Date.fromISOString != 'function') {
//method to handle conversion from an ISO-8601 style string to a Date object
// Date.fromISOString("2009-07-03T16:09:45Z")
// Fri Jul 03 2009 09:09:45 GMT-0700
Date.fromISOString = function(input) {
var date = new Date(input); //EcmaScript5 includes ISO-8601 style parsing
if (!isNaN(date)) return date;
//early shorting of invalid input
if (typeof input !== "string" || input.length < 10 || input.length > 40) return null;
var iso8601Format = /^(\d{4})-(\d{2})-(\d{2})((([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d{1,12}))?)?)?)?)?([Zz]|([-+])(\d{2})\:?(\d{2}))?$/;
//normalize input
var input = input.toString().replace(/^\s+/,'').replace(/\s+$/,'');
if (!iso8601Format.test(input))
return null; //invalid format
var d = input.match(iso8601Format);
var offset = 0;
date = new Date(+d[1], +d[2]-1, +d[3], +d[7] || 0, +d[8] || 0, +d[10] || 0, Math.round(+("0." + (d[12] || 0)) * 1000));
//use specified offset
if (d[13] == 'Z') offset = 0-date.getTimezoneOffset();
else if (d[13]) offset = ((parseInt(d[15],10) * 60) + (parseInt(d[16],10)) * ((d[14] == '-') ? 1 : -1)) - date.getTimezoneOffset();
date.setTime(date.getTime() + (offset * 60000));
if (date.getTime() <= new Date(-62135571600000).getTime()) // CLR DateTime.MinValue
return null;
return date;
};
}
Yes, to some degree as detailed here.
The approach I've used (pre-2008) is to do the conversion in the .NET business logic before inserting into the DB.
You can use GETUTCDATE() function to get UTC datetime
Probably you can select difference between GETUTCDATE() and GETDATE() and use this difference to ajust your dates to UTC
But I agree with previous message, that it is much easier to control right datetime in the business layer (in .NET, for example).
SUBSTRING(CONVERT(VARCHAR(34), SYSDATETIMEOFFSET()), 29, 5)
Returns (for example):
-06:0
Not 100% positive this will always work.
Sample usage:
SELECT
Getdate=GETDATE()
,SysDateTimeOffset=SYSDATETIMEOFFSET()
,SWITCHOFFSET=SWITCHOFFSET(SYSDATETIMEOFFSET(),0)
,GetutcDate=GETUTCDATE()
GO
Returns:
Getdate SysDateTimeOffset SWITCHOFFSET GetutcDate
2013-12-06 15:54:55.373 2013-12-06 15:54:55.3765498 -08:00 2013-12-06 23:54:55.3765498 +00:00 2013-12-06 23:54:55.373