Using Date to select a string - android studio - java - java

I'm trying to use a Date String to select a string to be displayed in my android app.
The Code im using to GET Date:
Calendar TextCalendar = Calendar.getInstance();
SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String TextDate = DateFormat.format(TextCalendar.getTime());
The Code im imagining I need to select strings:
TextView MyTextView = (TextView) findViewByID(R.id.my_text_view);
MyTextView.setText ( "DateVariable" + "Comment" )
This code I imagine not to work because I tried but, the bit with "DateVariable" And "Comment" means I could have Strings in Strings.xml Named Each Date but I would have 2 Strings for each day because there is a TITLE String and A Comment String, so i could imagine the string names looking like this
<string name="2016-02-28-TITLE">TESTING20160228</string>
<string name="2016-02-28-COMMENT">TESTING20160228Comment</string>
<string name="2016-02-29-TITLE">....
and so on
If anyone has a better suggestion on how to proceed with this it would be greatly appreciated.
Thanks ~Alexander

Try this:
String s = TextDate + "-Comment";
getString(getResources().getIdentifier(s, "string", getPackageName()));

Time Zone
Determining the current date requires a time zone. The date is not simultaneously the same around the world. A new day dawns earlier in the east. For example, in the first few minutes after midnight in Paris, it is still “yesterday” in Montréal.
If omitted, your JVM’s current default time zone is implicitly applied. That default can may vary, even during runtime! Better to be explicit with your desired/expected time zone.
java.time
You are using old date-time classes that have been supplanted by the java.time framework built into Java 8 and later. Much of java.time is back-ported to Java 6 & 7 and further adapted to Android.
These java.time classes include the LocalDate class for date-only values lacking a time-of-day and time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Your desired textual format complies with the ISO 8601 standard. The java.time classes use ISO 8601 by default when parsing/generating strings.
String output = today.toString() + "-Comment";
Java Naming
By the way, the code in your Question does not follow naming conventions. Class names should start with an uppercase while instance variable names should start with a lowercase.
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 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.

Related

find current Date and day after tomorrow's date in java

How to find current date in java. I found a lot but every time i got same command
Date d = new Date(); or something similar
Every such command returns a date of 1970 year.
I fail to understand, Whats the benefit of this getting a date of 1970 ?
Is there any way where i can get current time and add a second into it.
My real purpose is to convert a long value into Date and add a second in it.
5:40:12 should give me 5:40:13 after adding a second.
Any help would be appreciated as i am fed up getting 1970 date.
My real purpose is to convert a long value into Date and add a second in it. 5:40:12 should give me 5:40:13 after adding a second
The troublesome java.util.Date class is now legacy, supplanted by the java.time classes.
Instant.ofEpochMilli( yourLongIntegerGoesHere ) // A moment on the timeline in UTC represented a count of nanoseconds since the epoch of `1970-01-01T00:00:00Z`.
.atZone( ZoneId.of( "Pacific/Auckland" ) // Time zone for the region whose wall-clock time you want to see.
.plusSeconds( 1 )
.toLocalTime() // Extract just the time-of-day without date and without time zone.
.toString() // Generate a string representing the time-of-day value in standard ISO 8601 format.
05:40:13
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Java.Util.Date class is deprecated, I would recommend using
Java.Util.Calendar instead.
If you're looking to add a second to Current date, try something like this:
Calendar currentTime = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(currentTime.SECOND, 1);
System.out.println(currentTime.getTime());
BUT, the reason why you are receiving a 1970 date when using the Date class is because that class works with milliseconds, so you must multiply the long value by 1000 in order for it to convert to a date, here's an example.
Date currentDate = new Date( YourLongValue * 1000);

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.

Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]

This question already has answers here:
Java / convert ISO-8601 (2010-12-16T13:33:50.513852Z) to Date object
(4 answers)
Closed 6 years ago.
I am trying to parse a String using SimpleDateFormat.
This is my current code:
public String getCreatedDateTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-ddEHH:mm:ss.zzzz");
try {
Date date = simpleDateFormat.parse("2015-06-27T13:16:37.363Z");
return date.toString();
} catch (ParseException e) {
return "Error parsing date";
}
}
As you can see, I just put a constant in the parse() method for testing purposes.
So, this is what I am trying to parse:
2015-06-27T13:16:37.363Z
This is the SimpleDateFormat pattern that I am using:
yyyy-MM-ddEHH:mm:ss.zzzz
I keep getting the ParseException.
I know that it is proably because of the .zzzz at the end but I have no idea what .363Z might stand for so I just used some random letters. Bad idea.
I'll appreciate your help a lot. Thank you!
Try with this pattern (note the X at the end and the 'T' in the middle):
"yyyy-MM-dd'T'HH:mm:ss.SSSX"
From Java's SimpleDateFormat's documentation:
ISO 8601 Time zone:
...
For parsing, "Z" is parsed as the UTC time zone designator.
And, from the part where it describes the different characters:
X - Time zone - ISO 8601 time zone
EDIT
If using Android, then "X" is not supported.
You can use this pattern (note Z is a literal now):
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
But then you'll get the date on your current timezone and would need to convert it to UTC if needed.
tl;dr
Skip the formatting pattern. Standard ISO 8601 format is used by default.
Instant.parse( "2015-06-27T13:16:37.363Z" )
ISO 8601
Your string format is formally defined by the ISO 8601 standard.
Basically your Question is a duplicate of this one, Converting ISO 8601-compliant String to java.util.Date.
Alternatives
The Answer by eugenioy is correct.
But you should know that the old java.util.Date/.Calendar/java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome and should be avoided.
Outmoded Classes
Those old classes are now outmoded, first by the third-party Joda-Time library, and now by the new java.time package (Tutorial) built into Java 8 and later (inspired by Joda-Time, defined by JSR 310, extended by the ThreeTen-Extra project).
Both java.time and Joda-Time use the ISO 8601 standard as their defaults when parsing/generating string representations of date-time values. So the code is simple, no need for custom formatter objects. No need for all that format twiddling that caused your Exception.
Time Zone
Both java.time and Joda-Time have a zoned date-time class that understands its assigned time zone (unlike java.util.Date). If you do not assign one, the JVM’s current default time zone is assigned.
Beware that the JVM’s current default time zone can change at any time. It can change at deployment, defaulting to whatever the host OS setting is. And it can change at any moment during runtime when any code in any thread of any app within the JVM calls TimeZone.setDefault. So better to explicitly assign a desired/expected time zone.
java.time
The Z on the end of your string is short for Zulu and means UTC. The Instant class can directly parse that format, to represent a moment on the timeline in UTC with a resolution in nanoseconds.
String input = "2015-06-27T13:16:37.363Z";
Instant instant = Instant.parse( input );
Change the time zone from UTC to some desired/expected time zone.
ZoneID zone = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtMontréal = instant.atZone( zone ) ;
If you really need a java.util.Date for interoperability, convert.
java.util.Date utilDate = Date.from( zdtMontréal.toInstant() ) ;
Joda-Time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Example code using Joda-Time 2.8.1.
String input = "2015-06-27T13:16:37.363Z" ;
DateTimeZone zone = DateTimeZone.UTC ; // Or: DateTimeZone.forID( "America/Montreal" ) ;
DateTime dateTime = new DateTime( input, zone ) ;
If you really need a java.util.Date for interoperability, convert.
java.util.Date date = dateTime.toDate();
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Calendar timezone converting to GMT problem

I have one Calendar object which is as per the user's time zone which may be PST etc, now i want to convert the same to GMT and retain the time i.e. is the calendar initially was set # 00:00:00 at PST it should be converted to 08:00:00 after the conversion taking into consideration the time/date difference . Can someone provide me some help on this.
Appreciate the help in advance.
Thanks,
Vaibhav
Just create a new Calendar in GMT, set the time in that calendar to the same as the original calendar, and you're done:
gmtCalendar.setTime(userCalendar.getTime());
That should be fine, as the getTime() call returns the instant in time (i.e. a java.util.Date with no associated time zone).
As ever though, if you're doing any significant amount of date/time work in Java you should strongly consider using Joda Time instead.
tl;dr
( ( GregorianCalendar ) myCal ) // Cast from a general `Calendar` to specific subclass `GregorianCalendar`.
.toZonedDateTime() // Convert from troublesome legacy class to modern java.time class, `ZonedDateTime`.
.toInstant() // Extract a UTC-specific value, an `Instant` object.
java.time
The modern approach uses java.time classes.
Convert your legacy Calendar object (if GregorianCalendar) to a ZonedDateTime. Call new conversion methods added to the old classes.
GregorianCalendar gc = ( GregorianCalendar ) myCal ;
ZonedDateTime zdt = gc.toZonedDateTime() ;
Now extract an Instant, a value always in UTC. You can think of it this way conteptually: ZonedDateTime = ( Instant + ZoneId )
Instant instant = zdt.toInstant() ;
For more flexibility such as generating strings in various formats, convert to an OffsetDateTime object.
OffsetDateTime odt = instant.atOffset( ZoneOffset.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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.

Java / convert ISO-8601 (2010-12-16T13:33:50.513852Z) to Date object

How to parse a String in ISO 8601 format with Zulu time?
javax.xml.bind.DatatypeConverter.parseDateTime("2010-12-16T13:33:50.513852Z")
returns
IllegalArgumentException: '2010-12-16T13:33:50.513852Z' weist ein falsches Format auf.
Which mean something like wrong format, anyone have a clue what iss wrong in here?
tl;dr
Instant.parse( "2010-12-16T13:33:50.513852Z" )
java.time
The newer java.time classes can handle this string input.
The Z on the end is short for Zulu and means UTC, an offset of zero +00:00.
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.parse( "2010-12-16T13:33:50.513852Z" );
Time zone
You may want to apply a time zone ZoneId to get a ZonedDateTime. Search Stack Overflow for those class names to learn more, as well as for classes OffsetDateTime and DateTimeFormatter.
Conversion
Best to avoid the troublesome old legacy class of java.util.Date. But if you insist, call the new conversion methods added to the old classes.
java.util.Date date = java.util.Date.from( instant );
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.
It works for me try ide online
Output is :
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+00:00",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2010,MONTH=11,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=16,DAY_OF_YEAR=1,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=13,MINUTE=33,SECOND=50,MILLISECOND=513,ZONE_OFFSET=0,DST_OFFSET=0]
If the target Data Type is "ZonedDateTime", you can use the date-formatter "yyyy-MM-dd'T'HH:mm:ss.SSSSSSX". Example code as follows:
public ZonedDateTime convertStringToZonedDateTime() {
String inputString = "2010-12-16T13:33:50.513852Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSX");
ZonedDateTime zdt = ZonedDateTime.parse(inputString, formatter);
return zdt; //Output ZonedDateTime object is 2010-12-16T13:33:50.513852Z
}
Attention! If the input date-String has 0 as second and milli-second, for example "2010-12-16T13:00:00.000000Z", then the output ZonedDateTime object is "2010-12-16T13:00Z", even through it looks strange without second and milli-second, it is still a leagl ZonedDateTime.
If the target Data Type is "Instant":
public Instant convertStringToInstant() {
String inputString = "2010-12-16T13:33:50.513852Z";
Instant instant = Instant.parse(inputString);
return instant; //Output Instant object is 2010-12-16T13:33:50.513852Z
}
The code you posted works fine in my jre. Probably you defined your own DatatypeConverter (with german exception texts...!) and this specific DatatypeConverter cannot parse this date.
Do a codesearch for this code: DatatypeConverter.setDatatypeConverter( - there you will probably find your custom implementation of the "DatatypeConverterInterface" - which will then probably lead you to your bug.
Alternatively you can search for weist ein falsches Format auf. (because that exception text is not part of the jre)
Viel Erfolg ;)

Categories