从午夜到日期对象的秒数

时间:2014-08-27 17:58:51

标签: java date

我有一个方法从时间服务器加载时间并返回设置为该时间的日期对象。唯一的问题是,我从服务器获得的时间是午夜以来的秒。如何从午夜起设置日期对象?

public String timeserver = "time.nist.gov"; // Official U.S. Timeserver - Uses Time Protocol
    public Date load() {
        Socket reader;
        try {
            reader = new Socket(timeserver, 32);
            InputStreamReader isr = new InputStreamReader(reader.getInputStream());
            BufferedReader in = new BufferedReader(isr);
            long g = isr.read() & 0x00000000ffffffffL;
            Date d = new Date();
            //set d's time from g?

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

2 个答案:

答案 0 :(得分:1)

仅使用标准Java库,可以使用Calendar类完成:

// This gets you today's date at midnight
Calendar cal = Caledar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Next we add the number of milliseconds since midnight
long milliseconds = seconds * 1000;
cal.add(Calendar.MILLISECOND, milliseconds);

Date date = cal.getTime();

但是,如果它仍然是一个选项,我建议您考虑使用Joda-Time库。它has many advantages超过了内置的Date类,比如更简单的API。

在Joda-Time中,上述内容可以通过以下方式完成:

// Duration since midnight
long milliseconds = seconds * 1000;
Duration timeSinceMidnight = new Duration(milliseconds);

// Get the time of midnight today and add the duration to it
DateTime date = new DateMidnight().toDateTime();
date.plus(timeSinceMidnight);

答案 1 :(得分:0)

你可以尝试这个概念。它可能看起来效率不高,可以调整,但这是概念。

public static Date getDatefromSeconds(long seconds) {
    Date date;       
    long milliSecondsSinceMidnight = seconds*1000;

    Calendar now = Calendar.getInstance();
    now.set(Calendar.HOUR_OF_DAY,0);
    now.set(Calendar.MINUTE,0);
    now.set(Calendar.SECOND,0);
    now.set(Calendar.MILLISECOND,0);

    long timeobj = now.getTimeInMillis() + milliSecondsSinceMidnight;


    Calendar timedate = Calendar.getInstance();
    timedate.setTimeInMillis(timeobj);
    date = timedate.getTime();

    return date;
}