问题
I'm developing an Android app that uses a database, every time that the user insert a new register the current data and time is save in the db using
Calendar cal = Calendar.getInstance();
So, When I retrieve the data from the db, got a String like this:
java.util.GregorianCalendar[time=1496007575129,areFieldsSet=true,lenient=true,zone=America/Mexico_City,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=5,DAY_OF_MONTH=28,DAY_OF_YEAR=148,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=39,SECOND=35,MILLISECOND=129,ZONE_OFFSET=-21600000,DST_OFFSET=3600000]
The problem comes when I try convert that String using SimpleDateFormat.parse to display it in a RecyclerView, I get always the same date: 09/04/2017.
This is the code in my RecViewAdapter.java:
@Override
public void onBindViewHolder(ViewHolder holder,int position){
items.moveToPosition(position);
String s,d,p,f;
s = items.getString(ConsultaTomas.SISTOLICA);
holder.systolica.setText(s);
d = items.getString(ConsultaTomas.DIASTOLICA);
holder.diastolica.setText(d);
p = items.getString(ConsultaTomas.PULSO);
holder.pulso.setText(p);
f = items.getString(ConsultaTomas.FECHA);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
holder.fecha.setText(sdf.format(sdf.parse(f)));
}catch (ParseException e){
Log.d("PARSINGFECHA","Error al parcear fecha");
}
}
The other data is showed correctly in the RecView and the Calendar String are all diferent, so there is not the same date/hour in these strings. So, the question is:
How can I Convert Calendar.toString()
into date using SimpleDateFormat.parse()
?
This is the result running the app in a real device:
回答1:
You need to modify the way you store the Calendar
, call getTime()
and format it as desired to begin with. For example,
Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(sdf.format(cal.getTime()));
回答2:
tl;dr
( GregorianCalendar ) myCal // Cast the more general `Calendar` to subclass `GregorianCalendar`.
.toZonedDateTime() // Convert from terrible legacy class `GregorianCalendar` to its modern replacement `ZonedDateTime`.
.toLocalDate() // Extract just the date, without the time-of-day and without the time zone. Returns a `LocalDate` object.
.format( // Generate text representing the value of this `LocalDate` object.
DateTimeFormatter
.ofLocalizedDate( FormatStyle.SHORT ) // Automatically localize the text.
.withLocale( new Locale( "es" , "ES" ) ) // Specify a `Locale` to determine the human language and cultural norms to use in localization.
)
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible legacy classes Calendar
& GregorianCalendar
.
When you encounter a Calendar
object, immediately convert to its replacement, ZonedDateTime
, assuming your object is actually a GregorianCalendar
.
if( myCal instanceOf GregorianCalendar )
{
GregorianCalendar gc = ( GregorianCalendar ) myCal ; // Cast from more general class to the specific class.
ZonedDateTime zdt = gc.toZonedDateTime() ;
}
You apparently are interested only in the date portion, without the time-of-day and without the time zone. So extract a LocalDate
.
LocalDate ld = zdt.toLocalDate() ; // Ignore time-of-day and time zone.
Generate text in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;
Or better: Let java.time automatically localize for you.
Locale locale = new Locale( "es" , "ES" ) ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale ) ;
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. Hibernate 5 & JPA 2.2 support java.time.
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….
来源:https://stackoverflow.com/questions/44361292/how-can-i-convert-calendar-tostring-into-date-using-simpledateformat-parse