Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Created January 5, 2015 10:02
Show Gist options
  • Save ochinchina/763de4868faf5241cbe5 to your computer and use it in GitHub Desktop.
Save ochinchina/763de4868faf5241cbe5 to your computer and use it in GitHub Desktop.
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* time converter between the NTP time and the java date time class Calendar
*
* @author Steven Ou
*
*/
public class NTPTimeUtil {
private static final long NTP_GAP_SECONDS = 2208988800L;
/**
* convert the NTP time to Java Date time
* @param ntpSeconds NTP time in seconds
* @return the Calendar
*/
public Calendar toDateTime( long ntpSeconds ) {
Calendar cal = Calendar.getInstance( TimeZone.getTimeZone("UTC") );
cal.setTimeInMillis( ( ntpSeconds - NTP_GAP_SECONDS ) * 1000 );
return cal;
}
/**
* convert the date time <code>cal</code> to UTC time zone
* @param cal the date time
* @return the date time in UTC
*/
public static Calendar toUTC( Calendar cal ) {
TimeZone tz = cal.getTimeZone();
int offset = tz.getOffset( cal.getTimeInMillis() );
if( offset == 0 ) {
return cal;
} else {
GregorianCalendar gcal = new GregorianCalendar( TimeZone.getTimeZone("GMT") );
gcal.setTimeInMillis( cal.getTimeInMillis() + offset );
return gcal;
}
}
/**
* convert datetime to NTP time in seconds
* @param cal the date time
* @return the NTP time in seconds
*/
public long toNTPSeconds( Calendar cal ) {
return toUTC( cal ).getTimeInMillis()/1000 + NTP_GAP_SECONDS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment