Set Date to next day of week - java

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….

Related

Get the next date by specifying the day of week

I need to use calendar to do this approach, basicly i get the specific day of week (1,2,3) each int represents a day of week(Monday,Tuesday) not in this order, but the logic is this.
What i need is to get the date of the next day of week, imagine today is Monday, and the user select Wednsesday, i need to get the date of the next Wednesday.
My logic is this at the moment:
calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
dateMatch = calendar.getTime();
day of week is passed from a slidePicker, and represents the specific day of week, this DAY_OF_WEEK doesn't work, if i put Wednseday he gives me 6
Although your question text only says to find next dayOfWeek, your code also includes a time of day, in the form of hour and minute.
Assuming you want the first future occurrence of that combination, i.e. dayOfWeek, hour, and minute, that means that if today is that dayOfWeek, you either want today if time of day is later than now, or next week if time of day is earlier than now.
You can do that like this:
int dayOfWeek = Calendar.WEDNESDAY;
int hour = 10; // 10 AM
int minute = 0;
Calendar cal = Calendar.getInstance(); // Today, now
if (cal.get(Calendar.DAY_OF_WEEK) != dayOfWeek) {
cal.add(Calendar.DAY_OF_MONTH, (dayOfWeek + 7 - cal.get(Calendar.DAY_OF_WEEK)) % 7);
} else {
int minOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
if (minOfDay >= hour * 60 + minute)
cal.add(Calendar.DAY_OF_MONTH, 7); // Bump to next week
}
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal.getTime()); // Prints: Wed May 10 10:00:00 EDT 2017
tl;dr
To get the next Wednesday after today, or stick with today’s date if already a Wednesday.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
.with( TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) )
java.time
Use modern java.time classes that supplanted the troublesome old legacy date-time classes such as Calendar.
Use DayOfWeek enum objects to represent Monday-Sunday. Use smart objects rather than dumb integers to represent your day-of-week intention. Makes your code more self-documenting, ensures valid values, and provides type-safety.
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.
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" ) ;
LocalDate today = LocalDate.now( z ) ;
Use a TemporalAdjuster implementation such as TemporalAdjusters.nextOrSame to move to another date.
TemporalAdjuster ta = TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) ;
LocalDate nextOrSameWednesday = today.with( ta ) ;
If working with moments, use ZonedDateTime class rather than the awful Calendar class. Some idea as above, let the TemporalAdjuster do the heavy-lifting. But keep in mind that the time-of-day may be altered if that time-of-day is invalid for that new date such as during a Daylight Saving Time (DST) cut-over.
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
TemporalAdjuster ta = TemporalAdjusters.nextOrSame( DayOfWeek.WEDNESDAY ) ;
ZonedDateTime zdtSameOrNextWednesday = zdt.with( ta ) ;
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, 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.

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.

How to save and retrieve Date in SharedPreferences

I need to save a few dates in SharedPreferences in android and retrieve it. I am building reminder app using AlarmManager and I need to save list of future dates. It must be able to retrieve as milliseconds. First I thought to calculate time between today now time and future time and store in shared preference. But that method is not working since I need to use it for AlarmManager.
To save and load accurate date, you could use the long (number) representation of a Date object.
Example:
//getting the current time in milliseconds, and creating a Date object from it:
Date date = new Date(System.currentTimeMillis()); //or simply new Date();
//converting it back to a milliseconds representation:
long millis = date.getTime();
You can use this to save or retrieve Date/Time data from SharedPreferences like this
Save:
SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
Read it back:
Date myDate = new Date(prefs.getLong("time", 0));
Edit
If you want to store the TimeZone additionaly, you could write some helper method for that purpose, something like this (I have not tested them, feel free to correct it, if something is wrong):
public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) {
if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) {
return defValue;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(prefs.getLong(key + "_value", 0));
calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID())));
return calendar.getTime();
}
public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) {
prefs.edit().putLong(key + "_value", date.getTime()).apply();
prefs.edit().putString(key + "_zone", zone.getID()).apply();
}
You can do this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
To save a date:
preferences .edit().putString("mydate", sdf.format(date)).apply();
To retrieve:
try{
Date date = sdf.parse(preferences.getString("myDate", "defaultValue"));
} catch (ParseException e) {
e.printStackTrace();
}
Hope it help.
tl;dr
The modern approach uses java.time classes and ISO 8601 strings.
Reading.
Instant // Represent a moment in UTC with a resolution of nanoseconds.
.ofEpochMilli(
Long.getLong( incomingText )
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
Writing.
ZonedDateTime
.of(
LocalDate.of( 2018 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 35 ) ,
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Returns an `Instant`. Adjust from a time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
.toEpochMilli() // Returns a `long` integer number primitive. Any microseconds or nanoseconds are ignored, of course.
If your alarm manager has not yet been modernized to handle java.time objects, convert between legacy & modern classes using new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
java.time
The troublesome old date-time classes were supplanted by the java.time classes.
For a moment in UTC, with a resolution of nanoseconds, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
You want only milliseconds for your needs, so truncate any microseconds & nanoseconds.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ;
To determine a moment by date and time-of-day requires a 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.
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 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 ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Combine with a time-of-day, a LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
Wrap it all together as a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust to UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;
Extract your desired count-of-milliseconds since the epoch reference of first moment of 1970 in UTC. Again, be aware that any micros/nanos in your Instant will be ignored when extracting milliseconds.
long milliseconds = instant.toEpochMilli() ; // Be aware of potential data loss, ignoring any microseconds or nanoseconds.
Read those milliseconds back from storage as text using the Long class.
long milliseconds = Long.getLong( incomingText ) ;
Instant instant = Instant.ofEpochMilli( milliseconds ) ;
To see that moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate text representing that value, use DateTimeFormatter.ofLocalizedDateTime to automatically localize.
Tip: Consider writing your date-time values to storage in standard ISO 8601 format rather than as a count-of-milliseconds. The milliseconds cannot be read meaningfully by humans, making debugging & monitoring tricky.
String output = instant.toString() ;
2018-10-05T20:28:48.584Z
Instant instant = Instant.parse( 2018-10-05T20:28:48.584Z ) ;
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.

Calendar to date timezone problem

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.

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….

Categories