Given then timestamp 1245613885 that is a timestamp in GMT
How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?
Given then timestamp 1245613885 that is a timestamp in GMT
How do I turn that into Year, Day, Hour, Minute values in Java using the server's local timezone info?
You can use java.util.Calendar
for this. It offers a setTimeZone()
method (which is by the way superfluous since it by default already picks the system default timezone).
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
If you'd like to present it in a human readable date string, then I'd suggest SimpleDateFormat
for this.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
(the output is correct as per my timezone GMT-4)
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"), Locale.US);
calendar.setTimeInMillis(1245613885 * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DAY_OF_YEAR);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
Change the TimeZone
value you're passing into the Calendar
object's constructor if you need a different time zone.
Basically you just need a formatter to do this
Date date = new Date(1245613885L*1000);
SimpleDateFormat formatter = new SimpleDateFormat('MM/dd/yyyy');
System.out.println(formatter.format(date));
import java.util.Calendar;
import java.util.TimeZone;
public class Example{
public static void main(String[] args){
long utcTimestamp = 1285578547L;
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
cal.setTimeInMillis(utcTimestamp * 1000);
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.DAY_OF_YEAR));
System.out.println(cal.get(Calendar.HOUR));
System.out.println(cal.get(Calendar.MINUTE));
}
}
I would use something like Joda Time which is much faster than the JDK Date/Calendar classes and also doesn't have thread-safety issues with date parsing (not that your question relates to date parsing)