0

I have a method that loads the time from a timeserver and returns a date object set to that time. The only problem is, the time I get from the server is in Seconds Since Midnight. How do I set a date object from seconds since midnight?

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;
    }
Ethan McTague
  • 2,236
  • 3
  • 21
  • 53

2 Answers2

1

Using only the standard Java libraries, this can be done with the Calendar class:

// 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();

However if it is still an option, I would suggest that you consider using the Joda-Time library instead. It has many advantages over the built-in Date classes such as a simpler API.

In Joda-Time the above can be accomplished with:

// 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);
Community
  • 1
  • 1
0

You can try something along this concept. It may not look efficient and can be tweaked, but here is the concept.

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;
}
Start0101End
  • 108
  • 5