this is my date " 15-05-2014 00:00:00 "
how to convert IST to UTC i.e( to 14-05-2014 18:30:00)
based on from timezone to UTC timezone.
my code is
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("IST")); //here set timezone
System.out.println(formatter.format(date));
formatter.setTimeZone(TimeZone.getTimeZone("UTC")); //static UTC timezone
System.out.println(formatter.format(date));
String str = formatter.format(date);
Date date1 = formatter.parse(str);
System.out.println(date1.toString());
if user enter same date from any zone then will get UTC time(ex: from Australia then 15-05-2014 00:00:00 to 14-05-2014 16:00:00)
please any suggestions.
You cannot "convert that date values" to other timezones or UTC. The type java.util.Date does not have any internal timezone state and only refers to UTC by spec in a way which cannot be changed by user (just counting the milliseconds since UNIX epoch in UTC timezone leaving aside leapseconds).
But you can convert the formatted String-representation of a java.util.Date to another timezone. I prefer to use two different formatters, one per timezone (and pattern). I also prefer to use "Asia/Kolkata" in your case because then it will universally works (IST could also be "Israel Standard Time" which will be interpreted differently in Israel):
DateFormat formatterIST = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); // better than using IST
Date date = formatterIST.parse("15-05-2014 00:00:00");
System.out.println(formatterIST.format(date)); // output: 15-05-2014 00:00:00
DateFormat formatterUTC = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
System.out.println(formatterUTC.format(date)); // output: 14-05-2014 18:30:00
// output in system timezone using pattern "EEE MMM dd HH:mm:ss zzz yyyy"
System.out.println(date.toString()); // output in my timezone: Wed May 14 20:30:00 CEST 2014
tl;dr
LocalDateTime.parse(
"15-05-2014 00:00:00" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" )
)
.atZone( ZoneId.of( "Asia/Kolkata" ) )
.toInstant()
java.time
The Answer by Meno Hochschild is correct but shows classes that are now outdated.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "15-05-2014 00:00:00" , f ) ;
ldt.toString(): 2014-05-15T00:00
Apparently you are certain that string represents a moment in India time. Tip: You should have included the zone or offset in that string. Even better, use standard ISO 8601 formats.
Assign the India time zone.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2014-05-15T00:00+05:30[Asia/Kolkata]
To see the same moment, the same point on the timeline, through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ;
instant.toString(): 2014-05-14T18:30:00Z
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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
I have a webpage with a label like that: "Table last updated on Thu Jul 27 10:57:10 CEST 2017 from OWNER"
I have to check if this date is later than 0h today.
I'm getting the html code with:
Document doc = Jsoup.parse(driver.getPageSource());
String htmlcode = doc.body().text();
I thought about substringing the code to get the date, but since this label value can vary in size, I could not get the whole label.
Any ideas on how to get the date from the code, so I can compare it?
tl;dr
ZonedDateTime.parse( // Parse string into a date + time-of-day + time zone.
… , // Your input string.
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , Locale.US ) // Specify `Locale` to determine human language and cultural norms in parsing and translating the text.
)
.toLocalDate() // Extract the date-only portion of the `ZonedDateTime` object.
.isEqual(
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date as seen by people of a certain region (time zone).
)
java.time
The Answer by aUserHimself is correct in suggesting the use of jsoup library. But the example code is ill-advised in other ways, making these few mistakes:
Using troublesome legacy date-time classes. Those classes are now supplanted by the java.time classes.
Assumes the day starts at 00:00:00. Not true for all dates in all time zones. Anomalies such as Daylight Saving Time (DST) mean the day may start at a time such as 01:00:00.
Ignoring the issue of Locale, which determines the human language used in parsing the text of the name of month, name of day-of-week, etc. The Locale also determines the expected punctuation and other cultural norms.
Ignores the crucial issue of time zone in determining the current date.
Example code.
String input = … ;
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss zzz uuuu" , locale ) ;
ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;
LocalDate ld = zdt.toLocalDate() ;
Compare to today's date. Must specify the expected/desired time zone. For any given moment, the date varies around the world by zone. A new day dawns earlier in India than in Canada, for example.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
Boolean isSameDate = ld.isEqual( today ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.
Try something like this (prior to Java 8):
// get the label content as text (assuming you only have 1 label)
Document doc = Jsoup.parse(driver.getPageSource());
Element label = doc.select("label").first();
String labelText = label.text();
// get the relevant part (the date) from label content (between "on" and "from")
String dateString = labelText.split("on")[1].split("from")[0].trim();
// parse date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy", Locale.ENGLISH);
java.util.Date date = simpleDateFormat.parse(dateString);
// create calendar from label date
Calendar calendarLabel = new GregorianCalendar();
calendarLabel.setTime(date);
// create calendar for beginning of today in the default time zone
//Calendar calendarToday = Calendar.getInstance();
// or in a timezone of your choice
Calendar calendarToday = Calendar.getInstance(TimeZone.getTimeZone("Europe/Athens"));
calendarToday.set(Calendar.HOUR_OF_DAY, 0);
calendarToday.set(Calendar.MINUTE, 0);
calendarToday.set(Calendar.SECOND, 0);
calendarToday.set(Calendar.MILLISECOND, 0);
// find out if label date is later than 0h of today
System.out.println(calendarLabel.compareTo(calendarToday) >= 1);
For a more succinct solution in Java 8, see this answer of Basil Bourque.
This question already has answers here:
java.text.ParseException: Unparseable date
(10 answers)
Closed 6 years ago.
My date string is: "Wed Oct 19 14:34:26 BRST 2016" and I'm trying to parse it to "dd/MM/yyyy", but I'm getting the following exception:
java.text.ParseException: Unparseable date: "Wed Oct 19 14:34:26 BRST 2016" (at offset 20)
the method
public String dataText(int lastintervalo) {
Date mDate = new Date();
String dt = mDate.toString();
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.getDefault());
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
sdf.applyPattern("dd/MM/yyyy");
c.add(Calendar.DATE, lastintervalo);
return sdf.format(c.getTime());
}
I already searched on google and stackoverflow questions, but nothing seems to work
Since the error message is complaining about offset 20, which is the BRST value, it seems that it cannot resolve the time zone.
Please try this code, that should ensure that the Brazilian time zone is recognized:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(sdf.parse("Wed Oct 19 14:34:26 BRST 2016"));
Since I'm in Eastern US, that prints this for me:
Wed Oct 19 12:34:26 EDT 2016
tl;dr
ZonedDateTime.parse (
"Wed Oct 19 14:34:26 BRST 2016" ,
DateTimeFormatter.ofPattern ( "EE MMM dd HH:mm:ss z uuuu" )
)
.toLocalDate()
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT)
.withLocale( Locale.UK )
)
19/10/16
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Use real time zone
Never use the 3-4 letter abbreviation such as BRST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
Specify a proper time zone name in the format of continent/region. For example, America/Sao_Paulo.
So while the code below works in this particular case, I do not recommend exchanging data such as your input. If you have influence over the data source, change to using standard ISO 8601 formats for data exchange of date-time values.
2016-10-19T14:34:26-02:00
Even better, exchange strings as created by ZonedDateTime that extend ISO 8601 format by appending the time zone name in square brackets.
2016-10-19T14:34:26-02:00[America/Sao_Paulo]
Best of all, usually, is to convert such values to UTC before exchanging data. In java.time, call toInstant().toString() to do this. Generally best to work in UTC, applying a time zone only where required such as presentation to the user.
2016-10-19T16:34:26Z
Example code
String input = "Wed Oct 19 14:34:26 BRST 2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "EE MMM dd HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse ( input , f );
zdt.toString(): 2016-10-19T14:34:26-02:00[America/Sao_Paulo]
To see the same moment in UTC, extract a Instant.
Instant instant = zdt.toInstant();
instant.toString(): 2016-10-19T16:34:26Z
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
ld.toString(): 2016-10-19
To generate strings in other formats, search Stack Overflow for DateTimeFormatter class. Generally best to let java.time localize automatically.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US or Locale.ITALY etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT).withLocale( l );
String output = ld.format( f );
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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….
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.
Try this..It may work
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
I have a String representation of a local date time, and a Java TimeZone.
I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");
and
sdfZ.format(cal.getTime())
returns
08/14/2014 15:00:00-0400
which is EST.
Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?
Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)
You should try
sdfZ.setTimeZone(tz);
tl;dr
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Chicago" ) ) ;
String output = zdt.toInstant().toString() ;
2016-12-03T10:15:30Z
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Call toString to generate a String in standard ISO 8601 format. For example, 2011-12-03T10:15:30Z. This format is good for serializing date-time values for data storage or exchange.
String output = instant.toString(); // Ex: 2011-12-03T10:15:30Z
Time zone
Assign a time zone.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can skip over using Instant.
ZonedDateTime zdt = ZonedDateTime.now( z );
Calling toString on ZonedDateTime gets you an extended version of standard ISO 8601 format where the name of the time zone is appended in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
String output = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
DateTimeFormatter
The DateTimeFormatter class has a predefined formatter constant for your desired output: DateTimeFormatter.ISO_LOCAL_DATE_TIME
String output zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME );
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.
I am Having Date with it's timezone, I want to convert it to another Timezone, E.g. I have Date '3/15/2013 3:01:53 PM' which is in TimeZone 'GMT-06:00'. I want to convert this in 'GMT-05:00' timezone. I have search lot, and I am confuse about How actually Date is working. How to Apply timezone to date. I have try with SimpleDateFormat, Calender and also with offset.
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa XXX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM -06:00");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = df.format(dt);
System.out.println(newDateString);
It returns output
03/15/2013 09:01:53 AM Z.
I guess it should be
03/15/2013 09:01:53 PM Z, because time in 'GMT-06:00' timezone, so it should be HH+6 to get time in GMT. I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.Please Help me with example. Thanks in advance.
EDIT :
I am converting the string into date using SimpleDateFormat
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa");
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM");
} catch (ParseException e) {
e.printStackTrace();
}
Now, as you say, I specify to Calendar that my date is in 'GMT-06:00' timezone and set my date,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
cal.setTime(dt);
Now, I am telling calendar that I want date in 'GMT'
cal.setTimeZone (TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());
OutPut:
Fri Mar 15 03:01:53 CDT 2013
Please know me if i am going wrong.
You need TWO format objects, one for parsing and another one for printing because you use two different timezones, see here:
// h instead of H because of AM/PM-format
DateFormat parseFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
Date dt = null;
try {
dt = parseFormat.parse("3/15/2013 3:01:53 PM -06:00");
}catch (ParseException e) {
e.printStackTrace();
}
DateFormat printFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
printFormat.setTimeZone(TimeZone.getTimeZone("GMT-05"));
String newDateString = printFormat.format(dt);
System.out.println(newDateString);
Output: 3/15/2013 04:01:53 PM -05:00
If you want HH:mm:ss (24-hour-format) then you just replace
hh:mm:ss aaa
by
HH:mm:ss
in printFormat-pattern.
Comment on other aspects of question:
A java.util.Date has no internal timezone and always refers to UTC by spec. You cannot change it inside this object. A timezone conversion is possible for the formatted string, however as demonstrated in my code example (you wanted to convert to zone GMT-05).
The question then switches to the new requirement to print the Date-object in ISO-format using UTC timezone (symbol Z). This can be done in formatting by replacing the pattern with "yyyy-MM-dd'T'HH:mm:ssXXX" and explicitly setting the timezone of printFormat to GMT+00. You should clarify what you really want as formatted output.
About java.util.GregorianCalendar: Setting the timezone here is changing the calendar-object in a programmatical way, so it affects method calls like calendar.get(Calendar.HOUR_OF_DAY). This has nothing to do with formatting however!
tl;dr
OffsetDateTime.parse(
"3/15/2013 3:01:53 PM -06:00" ,
DateTimeFormatter.ofPattern( "M/d/yyyy H:mm:ss a XXX" )
).withOffsetSameInstant(
ZoneOffset.of( -5 , 0 )
)
2013-03-15T15:01:53-06:00
java.time
The Answer by Hochschild is correct but uses outdated classes. The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the modern java.time classes.
Parse your input string as a OffsetDateTime as it contains an offset-from-UTC but not a time zone.
String input = "3/15/2013 3:01:53 PM -06:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/yyyy h:mm:ss a XXX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2013-03-15T15:01:53-06:00
Tip: Save yourself some hassle and use the ISO 8601 formats when exchanging date-time data as text. The java.time classes use these standard formats by default when parsing/generating strings.
Apparently you want to see the same moment as viewed by the people elsewhere using a different offset-from-UTC.
ZoneOffset offset = ZoneOffset.of( -5 , 0 ) ;
OffsetDateTime odt2 = odt.withOffsetSameInstant( offset ) ;
We see the offset changes from 6 to 5, and the hour-of-day changes accordingly from 15 to 16. Same simultaneous moment, different wall-clock time.
odt2.toString(): 2013-03-15T16:01:53-05:00
Generating strings
I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.
I suggest you always include some indication of the offset or zoneunless your are absolutely certain the user understands from the greater context.
Your format is nearly in standard ISO 8601 format. You could define your own formatting pattern, but I would just do string manipulation to replace the T in the middle with a SPACE.
String output = odt2.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2013-03-15 16:01:53
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.
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")