package com.meldcraft.likejsr296;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class NetworkTimeRetriever
{
    public Date retrieveNetworkTime() throws IOException, ParseException
    {
        URL nistServer = new URL("http://time.nist.gov:13");
        InputStream is = nistServer.openStream();
        int ch = is.read();
        StringBuffer dateInput = new StringBuffer();;
        while(ch != -1) {
            dateInput.append((char)ch);
            ch = is.read();
        }
        String strDate = dateInput.substring(7, 24);
        DateFormat dateFormat = DateFormat.getDateTimeInstance();
        SimpleDateFormat sdf = (SimpleDateFormat)dateFormat;
        sdf.applyPattern("yy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT-00:00"));
        Date now = dateFormat.parse(strDate);
        return now;
    }
}



