Java Time/Date Conversion
- taolius
- May 25, 2018
- 1 min read
1. Java Calendar
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// get the supported ids for GMT-08:00 (Pacific Standard Time) String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); // if no ids were returned, something is wrong. get out. if (ids.length == 0) System.exit(0); // begin output System.out.println("Current Time"); // create a Pacific Standard Time time zone SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); // set up rules for Daylight Saving Time pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000); // create a GregorianCalendar with the Pacific Daylight time zone // and the current date and time Calendar calendar = new GregorianCalendar(pdt); Date trialTime = new Date(); calendar.setTime(trialTime);
2. Java Date
Date d1 = new Date();
Date d2 = new Date(System.currentTimeMillis());
long ts1 = d1.getTime();
d2 = d2.setTime(ts1);
3. Java Date Format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
dateFormat.format(new Date());
4. From String(DateFormat) to Date to Epoc Time
private static DateFormat uiDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String start_date = "2018-05-18 00:24:14";
try{ uiDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date start = uiDateFormat.parse(start_date); System.out.println(start.getTime()); } catch(Exception e){ }
5. Joda DateTime
Comments