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

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;
    }

最佳答案

仅使用标准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库。它在内置的Date类(例如更简单的API)上has many advantages

在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);

关于java - 自午夜至今的秒数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25534026/

10-08 22:05