Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the day, year, hours, min Individually from date format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"?

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,

like image 382
wolverine Avatar asked May 11 '12 13:05

wolverine


2 Answers

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

like image 81
Estragon Avatar answered Oct 13 '22 19:10

Estragon


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
like image 32
Joel Skrepnek Avatar answered Oct 13 '22 20:10

Joel Skrepnek