19

I am doing a programme that stores the present time and date in "yyyy-MM-dd'T'HH:mm:ss.SSSZ" this format. and I am storing it in database as a string. when i am collecting the data i need the individual values like day, year, min, seconds etc.. how can i do this?

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String now = formatter.format(new Date());

Thank you,

wolverine
  • 1,665
  • 5
  • 24
  • 43

4 Answers4

32

Just use parse instead of format :

String dateFromDB = "";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date yourDate = parser.parse(dateFromDB);

And then you can can read any field you want using java.util.Date & Calendar API :

  Calendar calendar = Calendar.getInstance();
    calendar.setTime(yourDate);
    calendar.get(Calendar.DAY_OF_MONTH); //Day of the month :)
    calendar.get(Calendar.SECOND); //number of seconds
//and so on

I hope it fits your needs

Estragon
  • 1,462
  • 11
  • 12
18

I'm suggesting that you store times in the DB as "timeInMillis". In my experience it simplifies code and it allows you to compare times values to eachother.

To store a time:

Calendar calendar = Calendar.getInstance(); // current time
long timeInMillis = calendar.getTimeInMillis();
mDb.saveTime (timeInMillis); // adjust this to work with your DB

To retrieve a time:

long timeInMillis = mDb.getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis (timeInMillis);
int milliSeconds = calendar.get(MILLISECOND);
//etc
Anish Kumar
  • 1,465
  • 16
  • 20
Joel Skrepnek
  • 1,651
  • 1
  • 13
  • 21
1

There are these methods available to get the individual parts of a date

getDate()
getMinutes()
getHours()
getSeconds()
getMonth()
getTime()
getTimezoneOffset()
getYear()
WingDev
  • 137
  • 5
  • These method was deprecated in API level 1. As of JDK version 1.1, To be replaced by using the following for ex: Calendar.get(Calendar.YEAR) - 1900. – this-Me Mar 17 '17 at 04:28
1

Try using : int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);

Here,

  • Calendar.HOUR_OF_DAY gives you the 24-hour time.
  • Calendar.HOUR gives you the 12-hour time.
Basher51
  • 1,319
  • 1
  • 17
  • 28