I have a date in UTC '2022-04-09 11:16:32' i want to convert it to IST it shouldbe '2022-04-09 04:46:32' in my code i'm using
String date = dataItem.getTime().replaceAll("-","/");
try {
DateFormat utcFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date d = utcFormat.parse(date);
DateFormat pstFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
pstFormat.setTimeZone(TimeZone.getTimeZone("IST"));
holder.date.setText(pstFormat.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
but it prints 2022/04/09 10:16:32 whis is not the actual time. please help me.
CodePudding user response:
tl;dr
LocalDateTime
.parse(
"2022-04-09 11:16:32"
.replace( " " , "T" )
)
.atOffset(
ZoneOffset.UTC
)
.atZoneSameInstant(
ZoneId.of( "Asia/Kolkata" )
)
.format(
DateTimeFormatter.ISO_LOCAL_DATE_TIME
)
.replace( "T" , " " )
See this code run live at IdeOne.com.
2022-04-09 16:46:32
Avoid legacy date-time classes
Never use the terrible legacy date-time classes such as Date
after altering the string to comply with ISO 8601 standard.
LocalDateTime
Parse your input as a LocalDateTime
.
String input = "2022-04-09 11:16:32".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
OffsetDateTime
Apparently you are certain that the supplied date-with-time string was intended to be a moment in UTC, having an offset of zero hours-minutes-seconds.
So apply an offset of zero, defined as a constant, to produce a OffsetDateTime
object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
Next you want to adjust from UTC into a particular time zone. Apply a ZoneId
to get a ZonedDateTime
. The result represents the same moment, the same point on the timeline, but with a date and time as seen in that time zone.
There is no such time zone as IST
. Nor CST
, PDT
, etc. These 2-4 character pseudo-zones are not real time zones. They are not standardized, and are not even unique! These are appropriate only for presentation to users, never for data exchange or data storage. Real time zones have name in format of Continent/Region
.
By IST
you might have meant Europe/Dublin
or Asia/Kolkata
.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
To generate your desired text, define your own custom formatting pattern with DateTimeFormatter
. Or use a predefined formatter for ISO 8601, and remove the T
.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
CodePudding user response:
It seems that "IST" is not in an available timezone id, you can check the list with: TimeZone.getAvailableIDs(). You can try with "Asia/Kolkata" instead.
pstFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));