How to parse Date in IST format in Golang? - parsing

time.Date(t.Year(), t.Month(), time.Now().Day(), 10, 0, 0, 0, time.UTC)
I want to set dateTime of 10:00:00 AM in IST format in golang.

It depends on the format of the time you have at hand. Go has some standard time formats ready as consts in the time package, but you can specify your own standard if it's custom. Regarding the time zone, you can parse or output a time in a specific time zone. Here is an example of parsing a time string in IST, and outputting it as UTC. It's not clear from your question what is your precise problem but I hope this helps:
// First, we create an instance of a timezone location object
loc, _ := time.LoadLocation("Asia/Kolkata")
// this is our custom format. Note that the format must point to this exact time
format := "Jan _2 2006 3:04:05 PM"
// this is your timestamp
timestamp := "Jun 25 2015 10:00:00 AM"
// now we parse it, considering it's in IST
t, err := time.ParseInLocation(format, timestamp, loc)
// printing it prints it in IST, but you can set the timezone to UTC if you want
fmt.Println(t, err)
// example - getting the UTC timestamp
fmt.Println(t.UTC())

Related

Moment Display Date according to ISO-8601 Timezone Offset

I am getting a ISO-8601 date string from an API response as follows :
var x1 = 2022-06-22T05:30:00+05:30
or it could be
var x2 = 2022-06-22T08:30:00-05:00
Irrespective of browser timezone I should display the dates as
X1 - 2022-06-22 05:30:30 IST
X2 - 2022-06-22 08:30:00 EST
How can i parse timezone from the offset like -05:00 or +05:30 using moment or luxon?
I tried moment.tz(timestamp) but it defaults to UTC since it needs the second argument.
So i did a bit more digging.
Logically what i want is not possible.
Many timezones shares UTC offset. Hence, there could be ambiguity, if we try to convert an offset to a TimeZone without any other additional info
Hence, I am opting for a solution, where my API response sends a timezone metadata for each date/time field. (I have lat/long info to convert in Tz in my backend)
In front End, i will simply use the timezone info to format my moment object into a desired date-time String.
For example
const timestring = '2022-06-22T00:00:00+00:00';
const timezoneName = "America/Chicago" ;
moment.tz(timestring, timezoneName).format('YYYY-DD-MM hh:mm:ss z');
// Output: 2022-06-21 07:00:00 CDT
Source : https://stackoverflow.com/tags/timezone/info

Transform Epoch UTC to String EST using momentjs

I have two input variables: an epoch time in UTC time zone and the name of the actual time zone. How do I get a formatted day/time using moment.js that would take in account the DST changes. I tried this code but it doesn't do the trick. What am I doing wrong, please?
var abs_time = 1611188219.277; // this is UTC coresponding to 1/21/2021 18:31:37 UTC
var timezone = "America/New_York"; // this the actual time zone
var mom = moment(abs_time * 1000).format();
var date_time = moment.tz(mom, timezone).format('ddd, MMM DD YYYY - HH:mm');
console.log(date_time);
//actual result: Thu, Jan 21 2021 - 18:31
//desired result: Thu, Jan 21 2021 - 13:31 - in the summer this should only be 4 hour difference
First, 1611188219.277 actually corresponds to 2021-01-21T00:16:59.277Z, not the time you gave in your question (assuming it is a Unix timestamp with seconds precision). This can be seen with the following code:
const d = new Date(1611188219.277 * 1000);
const s = d.toISOString();
console.log(s);
You can get the equivalent local time in a specific time zone without any libraries, as long as you're satisfied with the output produced by the toLocaleString function.
const d = new Date(1611188219.277 * 1000);
const s = d.toLocaleString(undefined, { timeZone: 'America/New_York' });
console.log(s);
Note that undefined in the above code will use the browser's current language. If you want a specific language, you could pass its language code there instead (such as en or en-US, etc.)
In general, due to its project status, you should avoid using Moment unless it's already being used in an existing project. If however, you must use Moment and Moment-TimeZone for this, you can do the following to get the same result:
const m = moment.tz(1611188219.277 * 1000, 'America/New_York');
const s = m.format('ddd, MMM DD YYYY - HH:mm');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data-10-year-range.min.js"></script>
I used the same format from your question, but of course you could change this as desired.
You might also consider using Luxon (the successor to Moment), or Date-fns, or several other libraries.
And yes, all of the above will correctly take daylight saving time into account.

What's the best way to convert LocalDate and LocalTime to java.util.date?

I have a org.threeten.bp.LocalDate and a org.threeten.bp.LocalTime and I do need a java.util.date instance. Whats the best way to archieve this. I looked through DateTimeUtils but found no proper solution.
Here is the better solution without using deprecated stuff but using the helper class DateTimeUtils:
// your input (example)
LocalDate date = LocalDate.of(2015, 4, 3);
LocalTime time = LocalTime.of(17, 45);
// the conversion based on your system timezone
Instant instant = date.atTime(time).atZone(ZoneId.systemDefault()).toInstant();
Date d = DateTimeUtils.toDate(instant);
System.out.println(d); // Fri Apr 03 17:45:00 CEST 2015
You need a timezone to make this conversion working. I have chosen the system timezone in the example given above but you are free to adjust the timezone to your needs.
Life can be so easy:
Date date = Date(localDate.year,localDate.monthValue,localDate.dayOfMonth,localTime.hour,localTime.minute, localTime.second)
edit: oh wait.... this is deprecated! So another solution would be better!

How to properly parse timezone codes

In the example bellow the result is always "[date] 05:00:00 +0000 UTC" regardless the timezone you choose for the parseAndPrint function. What is wrong with this code? The time should change depending on the timezone you choose. (Go Playground servers are apparently configured in UTC timezone).
http://play.golang.org/p/wP207BWYEd
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
parseAndPrint(now, "BRT")
parseAndPrint(now, "EDT")
parseAndPrint(now, "UTC")
}
func parseAndPrint(now time.Time, timezone string) {
test, err := time.Parse("15:04:05 MST", fmt.Sprintf("05:00:00 %s", timezone))
if err != nil {
fmt.Println(err)
return
}
test = time.Date(
now.Year(),
now.Month(),
now.Day(),
test.Hour(),
test.Minute(),
test.Second(),
test.Nanosecond(),
test.Location(),
)
fmt.Println(test.UTC())
}
When you Parse a time, you are parsing it in your current location, which is OK as long as that's what you're expecting, and the timezone abbreviation is known from within your location.
If you can forgo timezones, it's far easier to normalize all the times you're dealing with into UTC.
The next easiest is handling everything with explicit offsets, like -05:00.
If you want to deal with times originating in other timezones, you need to use time.Location. You can load Locations from the local timezone db with time.LoadLocation, and parse times there with time.ParseInLocation.
Question: How to properly parse time with abbreviated timezone names like UTC, CET, BRT, etc.?
Answer: You better should not. As JimB and others in this question Why doesn't Go's time.Parse() parse the timezone identifier? carefully suggest, you can expect that Go correctly parses only two timezones: UTC and the local one.
What they don't make quite explicit is that you can't expect Go to correctly parse time with any other timezone. At least that is so in my personal experience (go1.16.1, Ubuntu 20.04).
Also, abbreviated timezones are ambiguous. IST could mean India Standard Time, Irish Standard Time or Israel Standard Time. There's no way to disambiguate unless you know zone location, and, if you know location, you should use time.ParseInLocation.
If this is user input and you have control, you should change format requirements for users to input time with explicit offsets as JimB is also suggesting in their answer. Make sure you don't forget about minutes, i.e. use -0700, -07:00, Z0700 or Z07:00 but not -07 or Z07 in layout. Not all offsets are whole hours. For instance, Inidia Standard Time is UTC+5:30.
If you have no other choice and forced to parse such times, you can do something like that:
func parseTimeWithTimezone(layout, value string) (time.Time, error) {
tt, err := time.Parse(layout, value)
if err != nil {
return time.Time{}, err
}
loc := tt.Location()
zone, offset := tt.Zone()
// Offset will be 0 if timezone is not recognized (or UTC, but that's ok).
// Read carefully https://pkg.go.dev/time#Parse
// In this case we'll try to load location from zone name.
// Timezones that are recognized: local, UTC, GMT, GMT-1, GMT-2, ..., GMT+1, GMT+2, ...
if offset == 0 {
// Make sure you have timezone database available in your system for
// time.LoadLocation to work. Read https://pkg.go.dev/time#LoadLocation
// about where Go looks for timezone database.
// Perhaps the simplest solution is to `import _ "time/tzdata"`, but
// note that it increases binary size by few hundred kilobytes.
// See https://golang.org/doc/go1.15#time/tzdata
loc, err = time.LoadLocation(zone)
if err != nil {
return time.Time{}, err // or `return tt, nil` if you more prefer
// the original Go semantics of returning time with named zone
// but zero offset when timezone is not recognized.
}
}
return time.ParseInLocation(layout, value, loc)
}
Note that zone names that aren't present as files in timezone database will fail parsing. These are quite many. You can see what is present by checking
contents of /usr/share/zoneinfo, /usr/share/lib/zoneinfo on your system,
contents of this file https://github.com/golang/go/blob/master/lib/time/zoneinfo.zip.

parse "strange" date format

Hi I have trouble have parse date in this format:
1295716379
I don’t what kind of date format is it.
Human readable value of this string is:
22. 1. 2011, 18.12
Also I don’t know that this format is some cowboy coder format or it is some "standard".
And if it is possible parse string on the top to human readable format, for examle in C#, Java, C++.
Thank
It looks like a unix timestamp.
You can parse them like so:
C#: Parsing unix time in C#
C++: Converting a unix time to a human readable format
Java: Unix epoch time to Java Date object
Further links: Epoch Converter.com.
That's a UNIX Epoch timestamp.
An example in C# to convert it to a DateTime:
DateTime ToDateTime(int seconds)
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.ToLocalTime().AddSeconds(seconds);
}
This will convert it into local time.
Verified, it is a unix timestamp.
The time is Sat Jan 22 17:12:59 2011 in UTC.
It looks like you have a local time value and your timezone is UTC+1.
In C/C++:
#define _USE_32BIT_TIME_T
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
int i = atoi("1295716379");
time_t t = (time_t)i;
puts(ctime( &t ));
tm t_tm = *gmtime(&t);
puts(asctime( &t_tm ));
return 0;
}
Output:
Sun Jan 23 02:12:59 2011
Sat Jan 22 17:12:59 2011
Note that gmtime return UTC time value, localtime return local time value.
PS: I'm living in UTC+9 timezone

Resources