0

I searched topics about formatting time but these were all about Date class or DateTime. I am working with Time class. I created time as:

Time time = new Time(Time.getCurrentTimezone()) ;
time.setToNow();
String berkay = time.toString();
System.out.println(berkay);

When I execute it the output is :

20130417T070525GMT(3,106,0,0,1366182325)

actually date and time is correct (2013-04-17 07:05:25)

but I need to convert it into : 20130417070525 (My reason to do this is I will search database according to date so it is easier to compare times in that format)

How can I convert it?

4

3 回答 3

2

Try this:

Time time = new Time(System.currentTimeMillis()) ;  
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); 
String date = df.format(time).toString(); 
System.out.println(date); 

EDIT

But as smttsp suggested its much more efficient to store it as timestamp

于 2013-04-17T07:28:56.940 回答
1

To convert java.util.Date into String you should consider java.text.SimpleDateFormat.

For using java.util.Date as a parameter of a database query you should pass the Date as is without converting it into any other format.

passing Date parameter to create date range query <- In the answer there is sample how to create such query.

于 2013-04-17T07:31:47.530 回答
0

It is a bit late but if you are working on time and you need to compare or sort, the best way is to use Unix timestamp. It starts from 1-Jan-1970 00:00:00 and increments 1 each second.

It is a long value(64 bit) which is quite efficient to use in both time and space. Here is the website for Unix timestamp conversion.

Also 20130417070525 is 14 char string(at least 15 byte, I guess) and 1366182325 is long(8 byte). So go for long value. U can get it in that way

Date myDate = new Date(); // current time    
myDate.getTime();         // converts it to specified format.
于 2013-04-17T13:03:43.893 回答