Converts Local future/previous date in String to UTC date
A simple utility method to convert local time into UTC time. The important thing in this method is, you will find a lot of examples on the internet that changes the “current” local time to UTC time, but you will hardly find an example where you will change an old local time stored as string and change it to UTC time for that moment of time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public static String convertLocalTimeToUTC(String saleTimeZone, String p_localDateTime) throws Exception{ String dateFormateInUTC=""; Date localDate = null; String localTimeZone =""; SimpleDateFormat formatter; SimpleDateFormat parser; localTimeZone = saleTimeZone; //create a new Date object using the timezone of the specified city parser = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); parser.setTimeZone(TimeZone.getTimeZone(localTimeZone)); localDate = parser.parse(p_localDateTime); formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z'('Z')'"); formatter.setTimeZone(TimeZone.getTimeZone(localTimeZone)); System.out.println("convertLocalTimeToUTC: "+saleTimeZone+": "+" The Date in the local time zone " + formatter.format(localDate)); //Convert the date from the local timezone to UTC timezone formatter.setTimeZone(TimeZone.getTimeZone("UTC")); dateFormateInUTC = formatter.format(localDate); System.out.println("convertLocalTimeToUTC: "+saleTimeZone+": "+" The Date in the UTC time zone " + dateFormateInUTC); return dateFormateInUTC; } public static void main(String arg[]) throws Exception { convertLocalTimeToUTC("EST", "12-03-2013 10:30:00"); convertLocalTimeToUTC("PST", "12-03-2013 10:30:00"); } |
Hope this helps.