Calendar to date timezone problem - java

I have a date object which is parsed from a string using SimpleDateFormat("HH:mm").
This date has the correct time, but not the correct day (It's in January 1970), so i create a calendar with that date. Than i create a calendar with the current date and set the hours and minutes to the hours and minutes from the previous calendar.
If i now use newCal.getTime() it gives me the correct dates for times between 12:00 and 23:59 but if i for example give 11:00 i get a date with 23:00h which i cannot explain.
Here the full code:
String dateString = "11:00";
//String dateString = "20:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse(dateString,new ParsePosition(0));
Calendar parsedCal = Calendar.getInstance();
parsedCal.setTime(date);
Calendar newCal = Calendar.getInstance();
newCal.set(Calendar.HOUR, parsedCal.get(Calendar.HOUR));
newCal.set(Calendar.MINUTE, parsedCal.get(Calendar.MINUTE));
System.out.println(newCal.getTime());
For 20:00 i get the correct output for 11:00 i get 23:00 as mentioned.

You are using Calendar.HOUR; you should be using Calendar.HOUR_OF_DAY

Also,
String dateString = "11:00";
//String dateString = "20:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse(dateString);
Calendar parsedCal = Calendar.getInstance();
parsedCal.setTime(date);
Calendar newCal = Calendar.getInstance();
newCal.set(Calendar.HOUR, parsedCal.get(Calendar.HOUR));
newCal.set(Calendar.MINUTE, parsedCal.get(Calendar.MINUTE));
newCal.set(Calendar.AM_PM, parsedCal.get(Calendar.AM_PM));
System.out.println(newCal.getTime());

I'd recommend looking at Joda-time, which has classes representing date, time and date-time. Your code snippet could be replaced by:
String dateString = "11:00";
LocalTime time = new LocalTime(dateString);
System.out.println(time.toDateTimeToday());

tl;dr
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) , // Current date in a particular time zone.
LocalTime.parse( "23:00" ) , // Specify 11 PM.
ZoneId.of( "Pacific/Auckland" ) // Specify a time zone as the context for this date and time. Adjustments made automatically if that date-time is not valid in that zone.
)
2018-01-23T23:00+13:00[Pacific/Auckland]
java.time
The modern approach uses java.time classes instead of the troublesome old legacy date-time classes.
java.time.LocalTime
For a time-of-day only, without a date and without a time zone, use the LocalTime class.
LocalTime lt = LocalTime.parse( "23:00" ) ;
To determine a specific point on the timeline with that time-of-day, apply a date (LocalDate) and a time zone (ZoneId) to produce a ZonedDateTime object.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" );
Use that zone to get the current date.
LocalDate ld = LocalDate.now( z ) ;
ZonedDateTime
Combine.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
zdt.toString(): 2018-01-23T23:00+01:00[Africa/Tunis]
Keep in mind that for that particular zone, your date and time-of-day may not be valid. The ZonedDateTime class adjusts automatically. Study the doc to be sure you understand and agree with its algorithm for that adjustment.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Set Date to next day of week

I am using firebase and building a application with Android.
I have a DatePicker, where I can pick the day of week, hour and minutes.
When I pick the date and press submit, I want to store not the current date, or not even the date selected, but the next date related to the dayOfWeek chosen.
Imagine I choose Thursday, tomorrow is Thursday I want to save that date and the hour chosen by the current user either.
At the moment I tried something like this:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, dayOfWeek);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
dateMatch = calendar.getTime();
The hour and minutes are fine, but how can I store the next day/month/year?
tl;dr
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.next( DayOfWeek.THURSDAY ) ) ,
LocalTime.of( hours , minutes ) ,
ZoneId.of( "America/Montreal" )
).toString()
The ZonedDateTime class adjusts the time-of-day if invalid for that date in that zone.
java.time
The modern approach uses the java.time classes. Avoid the troublesome old legacy date-time classes seen in the Question.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Determine the DayOfWeek enum object represented by your UI widget. If tracking by number, that class numbers 1-7 for Monday-Sunday per ISO 8601 standard.
DayOfWeek dow = DayOfWeek.of( 1 ) ; // Monday=1.
Use a TemporalAdjuster found in TemporalAdjusters to determine the next date with that same day-of-week.
LocalDate ld = today.with( TemporalAdjusters.next( dow ) ) ;
Instantiate a LocalTime from your hours and minutes numbers.
LocalTime lt = LocalTime.of( hours , minutes );
Combine to determine an actual moment in the timeline.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Your particular time-of-day may not be valid for that date in that zone because of anomalies such as Daylight Saving Time (DST). The ZonedDateTime class adjusts as needed. Be sure to read the class doc to understand its policies in making that adjustment.
You can serialize that object to text using the standard ISO 8601 format, extended by this class to append the name of the time zone in square brackets.
String output = zdt.toString() ;
Reconstitute the object by parsing such strings.
ZonedDateTime zdt = ZonedDateTime.parse( input ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….

How to get time of the day, day of the week and month separately from sms query in android

I am extracting the date field from the sms table which returns the date as a time stamp,
but I wish to extract from the time stamp seprately
time of the day,
day of the week and
month of the year
I have read similar questions but none could help.
String date = cursor.getString(cursor.getColumnIndex("date"));
Long timestamp = Long.parseLong(date);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
Date finaldate = calendar.getTime();
String smsDate = finaldate.toString();
dateTextView.setText(smsDate);
int day= calendar.get(Calendar.DAY_OF_WEEK));
int month = calendar.get(Calendar.MONTH);
If you want to have the actual string value of month and the day, you can either use a switch to do that
Try the following,
String dayAsString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
String monthAsString = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Edit:
int hour12 = calendar.get(Calendar.HOUR); // 12
int hour24 = calendar.get(Calendar.HOUR_OF_DAY); //24
You can do calendar.MONTH, calendar.DAY and so.
you should use Joda Time:
http://www.joda.org/joda-time/
String date = cursor.getString(cursor.getColumnIndex("date"));
Long timestamp = Long.parseLong(date);
DateTime dateTime = new DateTime(timestamp);
int dayOfWeek = dateTime.getDayOfWeek();
int monthOfYear = dateTime1.getMonthOfYear();
tl;dr
Instant.ofEpochMilli( myCountOfMillis ) // Parse a count of milliseconds since first moment of 1970 in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Instantiate a `ZonedDateTime` object, having adjusted from UTC into a particular time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Or Locale.US, Locale.ITALY, etc. to determine human language and cultural norms in generating a localized string to represent this day-of-week.
lundi
java.time
Modern approach uses the java.time classes.
Assuming your long integer is a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z, instantiate a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochMilli( myCountOfMillis ) ;
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Apply your desired/expected time zone to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but with a different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Now you are in a position to interrogate for the parts of month, day-of-week, and time-of-day.
Month month = zdt.getMonth() ; // Get a `Month` enum object.
int m = zdt.getMonthValue() ; // Get an integer 1-12 for January-December.
DayOfWeek dow = zdt.getDayOfWeek() ; // Get a `DayOfWeek` enum object.
int dowNumber = zdt.getDayOfWeek().getValue() ; // Get a number for the day-of-week, 1-7 for Monday-Sunday per ISO 8601 standard.
String dowName = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Generate a localized string representing the name of this day-of-week.
LocalTime lt = zdt.toLocalTime() ; // Get a time-of-day object, without date, without time zone.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Calendar.add gives wrong year

My program takes the current date and then, in a loop, adds a week to that date and prints out the new date. Something like:
Calendar cal = Calendar.getInstance();
for (int i=0; i < 52; i++) {
cal.add(Calendar.DATE, 7);
// print date out
}
The add method works the way I expect it to until it reaches Dec 30, at which point the year jumps from 2012 to 2013.
so, using today's date of 4/16/2012, i tested a few different inputs:
this - cal.add(Calendar.DATE, 38*7);
yields- "date:1/7/2013"
this - cal.add(Calendar.DATE, 37*7);
yields- "date:12/31/2013"
this - cal.add(Calendar.DATE, 37*7-1);
yields- "date:12/30/2013"
this - cal.add(Calendar.DATE, 37*7-2);
yields- "date:12/29/2012"
so i notice that the year is correct up until dec 30 and dec 31, and then it corrects itself again when it gets back to january. is there a reason why it does this? does it have anything to do with 2012 being a leap year or am i misunderstanding the add method
Did you use SimpleDateFormat to print the date and use YYYY to produce the year? If so, that is where the problem lies. Because YYYY produces the week-year and not the calendar year. And as 30/12/2012 is in calendar week 1 of 2013, YYYY produces 2013. To get the calendar year, use yyyy in your SimpleDateFormat format string.
See https://bugs.openjdk.java.net/browse/JDK-8194625
tl;dr
Use modern java.time classes, never the terrible legacy classes such as Calendar.
LocalDate // Represent a date-only value with `LocalDate`, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.systemDefault() // Specify your desired/expected time zone explicitly.
) // Returns a `LocalDate` object.
.plusWeeks( 1 ) // Add a week, producing a new `LocalDate` object with values based on the original, per the immutable objects pattern.
.toString() // Generate text representing this date value in standard ISO 8601 format of YYYY-MM-DD.
2019-01-23
java.time
The modern approach uses the java.time classes.
The Calendar and GregorianCalendar classes are terrible, badly designed with flaws. Avoid them. Now replaced specifically by the ZonedDateTime class.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
To generate text representing that date value in standard ISO 8601 format, simply call toString.
String output = today.toString() ;
Date math is easy, with various plus… & minus… methods.
LocalDate weekLater = today.plusWeeks( 1 ) ;
You can also define a span of time as a Period or Duration. Then add that.
Period p = Period.ofWeeks( 1 ) ;
LocalDate weekLater = today.plus( p ) ;
Your example
Let's test out your example dates.
LocalDate ld = LocalDate.of( 2012 , Month.APRIL , 16 ) ;
Period period38Weeks = Period.ofWeeks( 38 ) ;
Period period37Weeks = Period.ofWeeks( 37 ) ;
Period period37WeeksLess1Days = period37Weeks.minusDays( 1 ) ;
Period period37WeeksLess2Days = period37Weeks.minusDays( 2 ) ;
LocalDate later_38 = ld.plus( period38Weeks ) ;
LocalDate later_37 = ld.plus( period37Weeks ) ;
LocalDate later_37_1 = ld.plus( period37WeeksLess1Days ) ;
LocalDate later_37_2 = ld.plus( period37WeeksLess2Days ) ;
Run code live at IdeOne.com. No problems. The 38th week is in 2013, while week 37 dates are in 2012.
later_38.toString(): 2013-01-07
later_37.toString(): 2012-12-31
later_37_1.toString(): 2012-12-30
later_37_2.toString(): 2012-12-29
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
It should be:
cal.add(Calendar.DAY_OF_YEAR, 7);
Calendar.DATE is same as Calendar.DAY_OF_MONTH.

how to pass hour, minute and second in calendar object in android java

i have made an application in which i need to perform date conversion.
Here is my code.
GregorianCalendar c = new GregorianCalendar(Locale.GERMANY);
c.set(2011, 04, 29,0,0,0);
String cdate = (String) DateFormat.format("yyyy-MM-dd HH:mm:ss", c.getTime());
Log.i(tag,cdate);
now when i check my LOG here is the output:
04-22 12:44:15.956: INFO/GridCellAdapter(30248): 2011-04-29 HH:00:00
why is the hour field not getting set. i have explicitly passed 0 when i was making the calendar object, still it is display HH in the LOG.
what could be the problem?
thank you in advance.
use lower-case hh:
String cdate = (String) DateFormat.format("yyyy-MM-dd hh:mm:ss", c.getTime());
set c.set(Calendar.HOUR_OF_DAY,0) and it should work.
Have you tried like this?
c.set(Calendar.YEAR, 2009);
c.set(Calendar.MONTH,11);
c.set(Calendar.DAY_OF_MONTH,4);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0)
tl;dr
LocalDate.of( 2011 , 4 , 29 ) // Represent April 29, 2011.
.atStartOfDay( ZoneId.of( "America/Montreal" ) ) // Determine the first moment of the day. Often 00:00:00 but not always.
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String representing the value of this date, using standard ISO 8601 format.
.replace( "T" , " " ) // Replace the `T` in the middle of standard ISO 8601 format with a space for readability.
Using java.time
The modern way is with the java.time classes.
If you are trying to get the first moment of the day, do not assume the time 00:00:00. Anomalies in some time zones mean the day may start at another time-of-day such as 01:00:00.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
You want a specific date in your Question.
LocalDate localDate = LocalDate.of( 2011 , 4 , 29 ) ;
Apply the time zone again in determining the first moment of the day.
ZonedDateTime zdt = localDate.atStartOfDay( z ); // Determine the first moment of the day on this date for this zone.
I recommend always including an indicator of the time zone or offset-from-UTC with your date-time strings. But if you insist, you can use a DateTimeFormatter predefined in java.time that does not include zone/offset: DateTimeFormatter.ISO_LOCAL_DATE_TIME. Merely remove the T from the middle.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….

Convert GMT to IST in java?

I have a GMT field in which the user enter a time to be converted to IST (for eg: in hour field 18, minute field 30, in session field am/pm). I need to get those inputs and convert to IST in java???
This is very easy and obvious if you realize that the timezone is only relevant for a date formatted as String - second/millisecond timestamps (of which java.util.Date is merely a wrapper) are always implicitly UTC (what GMT is properly called). And converting between such a timestamp and a string always uses a timezone, both ways.
So this is what you need to do:
DateFormat utcFormat = new SimpleDateFormat(patternString);
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat indianFormat = new SimpleDateFormat(patternString);
indianFormat .setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
Date timestamp = utcFormat.parse(inputString);
String output = indianFormat.format(timestamp);
tl;dr
OffsetDateTime.of(
LocalDate.now( ZoneOffset.UTC ) ,
LocalTime.of( 18 , 30 ),
ZoneOffset.UTC
).atZoneSameInstant( ZoneId.of( "Asia/Kolkata" ) )
Details
The modern approach uses the java.time classes.
Get the current date in UTC as a LocalDate without time-of-day and without time zone or offset.
LocalDate localDate = LocalDate.now( ZoneOffset.UTC );
Specify the time per user inputs as a LocalTime without a date and without a time zone or offset.
LocalTime localTime = LocalTime.of( 18 , 30 );
Put them together with an offset-from-UTC of zero, UTC itself as the constant ZoneOffset.UTC, to get an OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.of( localDate , localTime, ZoneOffset.UTC );
Apply a time zone as a ZoneId to get a ZonedDateTime for India time. Or by IST did you mean Irish Standard Time? Iran Standard Time?
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
See this code live at IdeOne.com.
localDate.toString(): 2017-02-13
localTime.toString(): 18:30
odt.toString(): 2017-02-13T18:30Z
zdt.toString(): 2017-02-14T00:00+05:30[Asia/Kolkata]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Well, joda-time is easier. Try something like this
DateTime dt = new DateTime(<year>,<month>,<day>, <hour>,<minute>, <second>, <millisecond>);
DateTime dtIST = dt.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("IST");
Note here that the use of the three letter abbreviation is deprecated and that time zones should be referred to like "America/Los_Angeles" refers to PST.I haven't the time to get the corrsesponding for IST right now but something should be left as an exercise to the reader!
UPDATE: As Basil Bourque states in the comments, Joda-Time is in maintenance mode. Use java.time instead.
When I add the below code, it worked for me.
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
DateFormat indianFormat = new SimpleDateFormat("dd-HH-mm");
utcFormat.setTimeZone(TimeZone.getTimeZone("IST"));
Date timestamp = utcFormat.parse("2019-04-26-19-00");
String istTime = indianFormat.format(timestamp);
If you'r looking for Indian TimeZone do this
"GMT+5:30"
val sdf = SimpleDateFormat("dd-MM-yyyy HH:mm:ss")
sdf.timeZone = TimeZone.getTimeZone("GMT+5:30")

Categories