2014-05-06 85 views
0

我的代码:使用日期,而不是时间戳

Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT")); 
    calendar.setTime(date); 
    calendar.set(Calendar.YEAR, 1970); 
    calendar.set(Calendar.MONTH, Calendar.JANUARY); 
    calendar.set(Calendar.DATE, 1); 
    date = calendar.getTime(); 
    Timestamp epochTimeStamp = new Timestamp(date.getTime()); 

我想消除在这种情况下使用时间戳,如何能实现与epochTimeStamp这里同样的事情,而无需使用的java.sql.Timestamp?我需要的格式与我使用Timestamp时相同。

+0

如果你正在谈论写日期的'String'表示的格式,你应该使用'SimpleDateFormat'来代替。 –

+2

你在做什么与时间戳? – jalynn2

+0

当你说你“需要格式相同”时,我们不知道你的意思。你能澄清一下吗? – pamphlet

回答

1

既然你需要你的DateString表示,然后使用SimpleDateFormatDate对象转换为String

Calendar calendar = ... 
//... 
date = calendar.getTime(); 
Timestamp epochTimeStamp = new Timestamp(date.getTime()); 
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
try { 
    System.out.println(sdf.format(date)); 
    System.out.println(sdf.format(epochTimeStamp)); 
} catch (Exception e) { 
    //handle it! 
} 

从你的榜样,打印

01/01/1970 09:21:18 
01/01/1970 09:21:18 
1

这给你一个时代时间与TimeStamp相同:

public class FormatDate { 

    public static void main(String[] args) { 

     DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS"); 
     LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0); 
     System.out.println(datetime.format(format)); 
    } 
} 
0

在Java中表示日期时间对象的另一种方法是使用Joda时间库。

import org.joda.time.LocalDate; 
... 

LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00"); 
//or DateTime startDate = new DateTime();// creates instance of current time 

String formatted = 
    startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss"); 

有几种方法可以做到格式,设置和使用这些库已经比使用JDK Date和Calendar库更可靠的获取时间。这些将持续在hibernate/JPA中。如果没有别的,这希望给你的选择。

相关问题