android Date + 14 and custom days - java

I have 4 Textview's (named date0, date1, date2 and date3) and 1 editText (name datex), I need code that will show me today date in date0 (dd,mmm,yyyy) , tomorrow in date1, today + 14days in date2.
For date3 I need code to put custom date from editext (named- datex), when click on datex, enter value 1,2 or any number(10 for example), and then show date in date3=today+10.
Thanks
(I could not get it from tutorials..., I have errors)
I do not have code.
It do not need to be saved, only to show dates. UTC date would be better if it is possible.

Today
Get the current date.
Specify a time zone (ZoneId) : for any given moment, the date varies around the globe by zone.
LocalDate today = LocalDate.now( ZoneOffset.UTC ) ;
Either specify custom formatting pattern (search Stack Overflow to learn more), or better, let java.time automatically localize. Specify a locale to determine the human language and cultural norms used for localization.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( locale ) ;
String outputToday = today.format( f ) ;
Tomorrow
Add a day to get tomorrow.
LocalDate tomorrow = today.plusDays( 1 ) ;
Generate text in the same manner as seen above.
String outputTomorrow = tomorrow.format( f ) ;
In two weeks
And add two weeks for future date.
LocalDate twoWeeksAhead = today.plusWeeks( 2 ) ;
Generate string as seen above.
All of this has been covered many many times already on Stack Overflow. So search to learn more.
See the code above run live at IdeOne.com.
outputToday: 7 nov. 2019
outputTomorrow: 8 nov. 2019
outputTwoWeeks: 21 nov. 2019
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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….

Related

Specify a date-time range with `Calendar` in Android

StackOverflow community,
I' currently working on my new project and I'm new to Java and Android Studio.
I have written my own Entry class with two Calendar variables.
Is there a shorter and cleaner way to create a new Entry object like in the following code?
//MainActivity.java
//....
private ArrayList<Entry> initEntrys() {
ArrayList<Entry> list = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
Calendar mStartDate = calendar;
Calendar mEndDate = calendar;
mStartDate.set(2019, 12, 20, 7, 0);
mEndDate.set(2019, 12, 20, 10, 0);
list.add(new Entry(mStartDate, mEndDate));
return list;
}
Any help would be really appreciated. :)
tl;dr
Never use the legacy date-time classes such as Calendar. Use only java.time classes.
For a date with time-of-day but lacking a time zone or offset-from-UTC, use java.time.LocalDateTime class.
LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 ) // year, month, day , hour , minute.
Avoid legacy date-time classes
Never use Calendar. That class is terrible, flawed in its design. It was supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
In contrast to the legacy classes, the java.time classes are immutable by design and therefore thread-safe.
Rather than use constructors with new, we instantiate java.time objects by calling static factory methods such as LocalDateTime.of.
Not a moment
If you are consciously working without the context of a time zone or offset-from-UTC, use LocalDateTime objects.
LocalDateTime start = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 ) ; // Passing year, month, day , hour , minute. The second and fractional-second both default to zero.
LocalDateTime stop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 ) ;
Moment
If you are trying to represent moments, specific points on the timeline, then LocalDateTime is the wrong class.
For tracking moments, you need the context of a time zone (or less preferably, an offset-from-UTC). For that, use ZonedDateTime as seen in the Answer by CrackerGen.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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….
I will try to complete Answer by Basil Bourque by covering a time zoned date using the ZonedDateTime class.
I have used UTC time zone in the example but you can customize with the suitable time zone you need.
LocalDateTime ldtStart = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 , 0 , 0 ) ;
ZonedDateTime ldtZonedStart = ldtStart.atZone(ZoneId.systemDefault());
ZonedDateTime utcZonedStart = ldtZonedStart.withZoneSameInstant(ZoneOffset.UTC);
LocalDateTime ldtStop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 , 0 , 0 ) ;
ZonedDateTime ldtStopZoned = ldtStop.atZone(ZoneId.systemDefault());
ZonedDateTime utcZonedStop = ldtStopZoned.withZoneSameInstant(ZoneOffset.UTC);

Getting different values for Timestamp.valueOf

I am trying to get the timestamp value for 2018-09-04 13:43:32.922000 by doing
Timestamp.valueOf("2018-09-04 13:43:32.922000")
my expected output is 2018-09-04 13:43:32.922
but I am getting 2018-09-04 01:13:32.922
It might be due to different timezone because my team in India got the exact result but I am here in California gets the different result.
Suggest the changes that can solve this problem.
tl;dr
myPreparedStatement.setObject(
Instant
.parse(
"2018-09-04 13:43:32.922000"
.replace( " " , "T" )
.concat( "Z" )
)
.atZone(
ZoneOffset.UTC
)
)
java.time
Suggest the changes that can solve this problem.
Never use java.sql.Timestamp.
Among the many flaws of that class is that the method you call is not documented to explain its behavior while parsing. It appears your JVM’s current default time zone is being silently applied with some adjustment. But the issue is moot.
That terribly-designed class was supplanted years ago by the modern java.time classes with the adoption of JSR 310, specifically Instant and OffsetDateTime.
Change your input string to standard ISO 8601 format by replacing the SPACE in the middle with a T.
String input = "2018-09-04 13:43:32.922000".replace( " " , "T" ) ;
Was your input intended to represent a moment in UTC, an offset of zero? If so, append a Z (pronounced Zulu).
String input = "2018-09-04 13:43:32.922000".replace( " " , "T" ).concat( "Z" ) ;
The Instant class represents a moment in UTC, always in UTC by definition.
Instant instant = Instant.parse( input ) ;
Your JDBC driver may optionally accept a Instant object.
myPreparedStatement.setObject( instant ) ;
If your JDBC driver does not support Instant, use OffsetDateTime. Support is required in JDBC 4.2 and later.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( odt ) ;
Notice how your JVM’s current default time zone at runtime is irrelevant, with no impact on the code above.
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.
I do not think the issue is due to different time zones. Its just that the output that you are getting is in 24 hour format and that needs to be converted to 12 hour format. Please refer How to convert 24 hr format time in to 12 hr Format? to convert the time to 12 hour format.

How to convert a string to date with UTC/GMT timezone

I have an android app that receives a string in this format:"MM-dd-yyyy HH:mm:ss" from my server. I want to convert this string to a Date object with UTC as timezone since the time in the string is UTC. I've already checked several similar questions but didn't find my answer
Here is what I'm using currently:
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
Date date = new Date();
try {
date = format.parse(itemContent [3]);
entity.setValidTill(date);
}catch (Exception e){
}
But what it does when I print that date with Log is show it as:
Sun Aug 27 15:00:00 GMT+04:00 2017
I want it to be:
Sun Aug 27 15:00:00 GMT 00:00 2017
So here is the main question how to get DateTime for UTC using a string with format as above?
Edit:
Just put it in a better context. I'm trying to get users to see the difference between current datetime & the that datetime saved in server. So my solution was to get gmt time for users & compare with the server time(which is gmt) so everyone see same difference regardless of their timezone. With C# you can get DateTime.UtcNow while with java I couldn't find an alternative
Briefly, as your Question is really a duplicate of many others…
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Parse your input string as a LocalDateTime as it lacks any indicator of offset-from-UTC or time zone.
Define a formatter to parse your input string.
String input = "08-27-2017 15:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2017-08-27T15:00
A LocalDateTime is not a moment on the timeline, only a rough idea about a range of possible moments. Has no meaning without the context of an offset (or time zone).
If you are certain that input was intended for UTC, assign the constant ZoneOffset.UTC for a OffsetDateTime.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
odt.toString(): 2017-08-27T15:00Z
To calculate a delta between that moment and the current moment, use the Period class for coarser granularity in your span of time, or Duration for finer granularity. Both classes generate strings in standard ISO 8601 format of PnYnMnDTnHnMnS.
OffsetDateTime now = OffsetDateTime.now( ZoneOffset.UTC ) ;
Duration d = Duration.between( odt , now ) ;
now.toString(): 2017-08-27T21:16:56.396Z
d.toString(): PT6H16M56.396S
See this code run live at IdeOne.com.
In the standard strings seen above, the Z is short for Zulu and means UTC.
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….
just add this code under the first line of your code:
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Java SWT DateTime: Determine day of Week

I have a DateTime widget with 3/9/2017. Based on the documentation for DateTime, I don't see a way to determine the day of the week. I'll eventually need a string parsed in this format "Wed Feb 22 14:57:34 UTC 2017" from the DateTime widget, but the first step is to get the day of the week. Is there a way to do this outside of making my own function? And if not, what would you recommend as the best approach for the function, since days of the week are not consistent to dates from year to year?
Let me know if you need any addition information.
Thank you!
Use java.util.Calendar:
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Documentation
tl;dr
LocalDate.of( 2017 , Month.MARCH , 9 )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.ITALY )
Or…
OffsetDateTime.now( ZoneOffset.UTC )
.format( DateTimeFormatter.RFC_1123_DATE_TIME )
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes.
The DayOfWeek enum defines seven objects, one for each day of the week, Monday-Sunday.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DayOfWeek dow = LocalDate.now().getDayOfWeek() ;
Generate a string of the localized name.
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US etc.
To generate your longer string for a moment, use DateTimeFormatter to specify a custom pattern, use a built-in pattern, or automatically localize.
String output = OffsetDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.RFC_1123_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.
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.

Joda-Time Formatting for Islamic Date

I am using Joda-Time to get the Islamic date in the dd MMMM yyyy but I am always getting dd MM yyyy.
Any advise? could it be that Hijri dates are not supported for formatting? It's not clear on the Joda-Time website.
DateTime dtISO = new DateTime(2014,2,25,0,0,0,0);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance());
String formatIslamic= "dd MMMM yyyy";
DateTimeFormatter formatter = DateTimeFormat.forPattern(formatIslamic).withChronology( IslamicChronology.getInstance());
String islamicDateString = formatter.print(dtIslamic);
This is currently not implemented. The BasicChronology class sets the monthOfYear field to use GJMonthOfYearDateTimeField which in turn gets it's data from java.text.DateFormatSymbols. The IslamicChronology uses a sets the monthOfYear field to a BasicMonthOfYearDateTimeField which has the following implementation of getAsText:
public String getAsText(int fieldValue, Locale locale) {
return Integer.toString(fieldValue);
}
What someone needs to do is to create a IslamicMonthOfYearDateTimeField that extends BasicMonthOfYearDateTimeField and overrides the method so that it returns the name of the month rather than the numeric value of the month. This could either be done in the joda-time codebase, or completely outside. To get this working outside of joda, just extend IslamicChronology and override assemble to pull in your new IslamicMonthOfYearDateTimeField. I'd issue a pull request to joda-time myself, but I doubt they'd accept a non-localized solution.
tl;dr
java.time.chrono.HijrahDate.from(
LocalDate.of( 2014 , 2 , 25 )
)
.get( ChronoField.YEAR )
1435
java.time
The Joda-Time project is now in maintenance mode, advising migration to the java.time classes.
The java.time classes offer a HijrahChronology and HijrahDate in the java.time.chrono package.
For Java 6 & 7, and for earlier Android, the ThreeTen-Backport project also offers a HijrahChronology and HijrahDate.
LocalDate ld = LocalDate.of( 2014 , 2 , 25 ) ;
HijrahDate hd = HijrahDate.from( ld );
String output = hd.toString() ;
output: Hijrah-umalqura AH 1435-04-25
As for other formats, the format method with DateTimeFormatter seem to revert to ISO chronology.
Locale locale = Locale.forLanguageTag( "en-US-u-ca-islamic-umalqura" );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale );
String output2 = hd.format( f );
output2: Tuesday, February 25, 2014
While I do not have time at the moment to do so, I suggest looking at the source code of the HijrahDate::toString method.
You can roll-your-own formatting by using the example code as seen in the java.time.chrono package documentation.
int day = hd.get( ChronoField.DAY_OF_MONTH );
int dow = hd.get( ChronoField.DAY_OF_WEEK );
int month = hd.get( ChronoField.MONTH_OF_YEAR );
int year = hd.get( ChronoField.YEAR );
System.out.printf( "%s %s %d-%s-%d%n" , hd.getChronology().getId() , dow , day , month , year );
Hijrah-umalqura 2 25-4-1435
See also:
Convert Jalali calendar to Georgian in java
Get a gregorian date from Hijri date strings
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.

Categories