Save and retrieve date in android

//To obtain shared preferences
SharedPreferences prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
//To read preferences
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
System.out.println("_____fecha de pref"+l);

//long to Date
Date datata = new Date(l);
System.out.println("Data convert of long to date"+datata);

// Date to Calendar
Calendar t1=Calendar.getInstance();
t1.setTime(datata);
System.out.println("convert date to calendar"+t1.getTime());

Calendar t2 = Calendar.getInstance();
System.out.println("second date"+t2.getTime());

//deduct date
int second = t2.get(Calendar.SECOND) - t1.get(Calendar.SECOND);
System.out.println("the seconds:"+second);

//To edit and save preferences
Date dato = new Date();
System.out.println("el dato:"+dato);
prefs.edit().putLong(dateTimeKey, dato.getTime()).commit();

Leave a Reply

Your email address will not be published. Required fields are marked *