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")
Related
I have method to find month end date based on the timezone.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
);
System.out.println(calendar.getTime());`
It displays output: Thu Aug 30 18:04:54 PDT 2018.
It should, however, give me an output in CET.
What am I missing?
The Calendar.getTime() method returns a Date object, which you then printed in your code. The problem is that the Date class does not contain any notion of a timezone even though you had specified a timezone with the Calendar.getInstance() call. Yes, that is indeed confusing.
Thus, in order to print a Date object in a specific timezone, you have to use the SimpleDateFormat class, where you must call SimpleDateFormat.setTimeZone() to specify the timezone before you print.
Here's an example:
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class TimeZoneTest {
public static void main(String argv[]){
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("calendar.getTime(): " + calendar.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
System.out.println("sdf.format(): " + sdf.format(calendar.getTime()));
}
}
Here is the output on my computer:
calendar.getTime(): Fri Aug 31 01:40:17 UTC 2018
sdf.format(): 2018-Aug-31 03:40:17 CEST
This is because Date object doesn't have timezone as part of its state, and getTime() actually returns a date which corresponds to the JVM's timezone, instead you need SimpleDateFormat to format and print the date in your required timezone.
If you try adding the following line of code, you could see that the timezone in the calendar is actually CET.
System.out.println(calendar.getTimeZone().getDisplayName());
tl;dr
YearMonth // Represent a year-month without day-of-month.
.now( // Capture the current year-month as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Africa/Tunis" ) // Specify your desired time zone. Never use 3-4 letter pseudo-zones such as `CET`.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determine the last day of this year-month. Returns a `LocalDate` object.
.atStartOfDay( // Let java.time determine the first moment of the day. Not necessarily 00:00:00, could be 01:00:00 or some other time-of-day because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object, representing a date, a time-of-day, and a time zone.
java.time
You are using the terrible old Calendar class that was supplanted years ago but the modern java.time classes.
LocalDate
If you need only a date, use LocalDate class. Then the time zone is irrelevant for your output.
But time zone is very relevant for determining the current date. For any given moment, the date varies around the globe by zone.
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 CET or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" ) ; // Or "Africa/Tunis" etc.
LocalDate today = LocalDate.now( z ) ; // Capture the current date as seen by the wall-clock time used by the people of a certain region (a time zone).
YearMonth
Get the month for that date. Represent a year-month with, well, YearMonth.
YearMonth ym = YearMonth.from( today ) ;
Or skip the LocalDate.
YearMonth ym = YearMonth.now( z ) ;
Get the end of the month.
LocalDate endOfThisMonth = ym.atEndOfMonth() ;
ISO 8601
To generate a String representing that LocalDate object’s value, call toString. The default format is taken from the ISO 8601 standard. For a date-only value that will be YYYY-MM-DD such as 2018-01-23.
String output = endOfThisMonth.toString() ;
If you need another format, use DateTimeFormatter class. Search Stack Overflow for many examples and discussions.
Moment
If you need a moment, you can add a time-of-day and time zone to your LocalDate to get a ZonedDateTime. Or let ZonedDateTime determine the first moment of the day (which is not always 00:00:00!).
ZonedDateTime zdt = LocalDate.atStartOfDay( z ) ;
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, 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 (<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.
I have seen many resources on this but one thing I cant get is when converting the millisecond timestamp, how I add a corresponding time zone, during the conversion process.
Date date = new Date(Long.valueOf(dateInMil*1000L);
SimpleDateFormat myDate = new SimpleDateFormat("EEE, MMM d, ''yy");
String formatted = myDate.format(date);
Now if I have a time zone/offset in string formate i.e. "-04:00" or "+2:00" how to apply it to the above so I can get the proper date ?
tl;dr
Instant.ofEpochMilli( myCountOfMilliseconds )
.atZone( ZoneId.of( "Africa/Tunis" ) )
.toString()
java.time
The modern approach uses the java.time classes rather than the troublesome old Calendar/Date classes that are now legacy.
Assuming your count of milliseconds is a count since the epoch reference of first moment of 1970 in UTC (1970-01-01T00:00), then parse as 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( myCountOfMilliseconds ) ;
To move from UTC to another time zone, apply a ZoneId to get a ZonedDateTime.
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" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Objects vs text
After assigning the time zone, then generate a string in your desired format (not before). You may be conflating date-time values (objects) with strings representing their value textually. Learn to think of smart objects, not dumb strings.
DateTimeFormatter
To generate a String in a particular format, use a DateTimeFormatter. Search Stack Overflow as this been covered many many times, as have the other concepts shown here. Of special note are the DateTimeFormatter.ofLocalized… methods.
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.
I was doing a similar thing in my previous project.You can use setTimeZone method of SimpleDateFormat class. Something like this :
mydate.setTimeZone(TimeZone.getTimeZone("GMT -0400"));
DateTimeFormatter myDateFormatter
= DateTimeFormatter.ofPattern("EEE, MMM d, ''yy", Locale.ENGLISH);
long dateInSec = 1_554_321_098L;
String utcOffsetString = "-04:00";
ZoneOffset offset = ZoneOffset.of(utcOffsetString);
String date = Instant.ofEpochSecond(dateInSec)
.atOffset(offset)
.format(myDateFormatter);
System.out.println(date);
This prints
Wed, Apr 3, '19
The other example offset you gave, +2:00, is slightly more difficult since ZoneOffset.of requires either only hours (+2) or two-digit hours before the colon (+02:00). One solution is to fix the string before handing it to ZoneOffset:
String utcOffsetString = "+2:00";
utcOffsetString = utcOffsetString.replaceFirst("([-+])(\\d:\\d{2})", "$10$2");
ZoneOffset offset = ZoneOffset.of(utcOffsetString);
The result is still Wed, Apr 3, '19. If there were already 2-digit hours in the string, replaceFirst won’t replace anything, so you just get the same string back.
If I change the offset to +08:00, I get Thu, Apr 4, '19 instead.
Edit: I frankly find the regular expression I use for fixing the offset string quite unreadable. Here’s a simpler way of fixing it:
DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("O", Locale.ENGLISH);
ZoneOffset offset = ZoneOffset.from(offsetFormatter.parse("GMT" + utcOffsetString));
Like Basil Bourque I am using java.time. See all the details in his answer.
Not exactly what your looking for but close
String timeZone = "America/Los_Angeles"
TimeZone tz = TimeZone.getTimeZone(timeZone);
SimpleDateFormat sdf = new SimpleDateFormat("EEEEE MMMMM d hh:mm a");
sdf.setTimeZone(tz);
Date localizedTime = sdf.format(new Date());
If you keep the localization strings instead of the offsets this will work. Or you can make a map.
Given a DateTime for example 2015-07-09T05:10:00+02:00 using Joda-Time?
How can I convert it to local time, meaning adding the timezone to the time itself.
Desired output: 2015-07-09T07:10:00
I tried dateTime.toDateTime(DateTimeZone.UTC) but that did not give the desired result.
Adding a bit more info and examples to the correct answers (accepted answer and other one).
UPDATE Added section at end on java.time classes. These supplant Joda-Time.
Purpose of LocalDateTime
You may be confused about the purpose of LocalDateTime.
If trying to represent a date-time value using "wall clock time" as seen by someone in a locality looking at their own clock and calendar, then adjust the time zone of the DateTime object to suit the desired locality.
LocalDateTime is not meant for a particular locality but for the general idea of date+time. For example, "This year's Christmas starts at midnight on December 25, 2014". Conceptually, that is a LocalDateTime, intended to mean different moments in Paris than Montréal and Auckland.
Adjusting Time Zone
Use the DateTimeZone class in Joda-Time to adjust to a desired time zone. Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone).
Use proper time zone names. Generally a continent/cityOrRegion.
DateTimeZone zoneParis = DateTimeZone.forID( "Europe/Paris" );
DateTimeZone zoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTimeZone zoneAuckland = DateTimeZone.forID( "Pacific/Auckland" );
Parse string, assign a time zone, adjust to other time zones.
DateTime dateTimeParis = new DateTime( "2015-07-09T05:10:00+02:00" , zoneParis );
DateTime dateTimeMontréal = dateTimeParis.withZone( zoneMontréal );
DateTime dateTimeAuckland = dateTimeParis.withZone( zoneAuckland );
Dump to console.
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeAuckland: " + dateTimeAuckland );
When run.
dateTimeParis: 2015-07-09T05:10:00.000+02:00
dateTimeMontréal: 2015-07-08T23:10:00.000-04:00
dateTimeAuckland: 2015-07-09T15:10:00.000+12:00
Localize Using Formatted Strings
Joda-Time can translate to a particular locale’s language and customary style when creating a string representation of your date-time object.
DateTimeFormatter formatterMontréal = DateTimeFormat.forStyle( "FF" ).withZone( zoneMontréal ).withLocale( Locale.CANADA_FRENCH );
String outputMontréal = formatterMontréal.print( dateTimeParis );
System.out.println( "outputMontréal: " + outputMontréal );
When run:
outputMontréal: mercredi 8 juillet 2015 23 h 10 EDT
java.time
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. The Joda-Time framework inspired java.time, so concepts are quite similar.
ZoneId and ZoneOffset are the two classes to represent a time zone and offset-from-UTC respectively. An offset is merely a number of hours and minutes and seconds. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
ZoneId zoneParis = ZoneId.of( "Europe/Paris" );
ZoneId zoneMontreal = ZoneId.of( "America/Montreal" );
ZoneId zoneAuckland = ZoneId.of( "Pacific/Auckland" );
The primary date-time classes in java.time are:
Instant – A moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
OffsetDateTime – An Instant plus a ZoneOffset.
ZonedDateTime – An Instant plus a ZoneId.
The java.time classes use ISO 8601 standard formats by default when parsing/generating strings representing date-time values. So no need to specify a formatting pattern with such inputs.
This input here indicates an offset-from-UTC but not a full time zone. So we parse as an OffsetDateTime rather than a ZonedDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2015-07-09T05:10:00+02:00" );
As the basic building-block of java.time, always in UTC by definition, you may want to extract an Instant.
Instant instant = odt.toInstant(); // `Instant` is always in UTC by definition.
You can adjust into a time zone.
ZonedDateTime zdtParis = odt.atZoneSameInstant( zoneParis );
ZonedDateTime zdtMontreal = odt.atZoneSameInstant( zoneMontreal );
ZonedDateTime zdtAuckland = zdtMontreal.withZoneSameInstant( zoneAuckland );
Localize via the DateTimeFormatter class.
DateTimeFormatter f = DateTimeformatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH );
String output = zdtMontreal.format( f );
See live code in IdeOne.com.
odt: 2015-07-09T05:10+02:00
instant: 2015-07-09T03:10:00Z
zdtParis: 2015-07-09T05:10+02:00[Europe/Paris]
zdtMontreal: 2015-07-08T23:10-04:00[America/Montreal]
zdtAuckland: 2015-07-09T15:10+12:00[Pacific/Auckland]
output: mercredi 8 juillet 2015 23 h 10 EDT
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….
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.
What #Nazgul said is right, but in case all you want to achieve is a "wall-time" in UTC zone you can do something like that:
DateTime dateTimePlus2 = DateTime.parse("2015-07-09T05:10:00+02:00");
System.out.println(dateTimePlus2);
DateTime dateTimeUTC = dateTimePlus2.withZone(DateTimeZone.UTC);
System.out.println(dateTimeUTC);
LocalDateTime localDateTimeUTC = dateTimeUTC.toLocalDateTime();
System.out.println(localDateTimeUTC);
Result:
2015-07-09T05:10:00.000+02:00
2015-07-09T03:10:00.000Z ("Z" == Zulu tz == UTC)
2015-07-09T03:10:00.000
As you can see, the time is not "07:10" as you expected, because UTC+2 zone is two hours ahead of UTC. Converting to UTC subtracts 2 hours.
DateTime without timezone dosnt make sense. DateTime are always relative to the timezone in which they are used. Without the timezone information a date time combination makes no sense for the geography as such. raw timestamp millies can however be accessed as the number of millies gone since 1st Jan 1970 but any concrete date time combinations must have a timezone with it.
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.
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….