Showing posts with label Time in JAVA. Show all posts
Showing posts with label Time in JAVA. Show all posts

Monday, February 18, 2008

Calculate time according to Locale in JAVA

We Often get confuse in calculating time ?
For eg: If I ask you what is the Time in New York by now? If you are not in New York, then it will be a problem? Here is the code that can be used to find time in any part of the world..Enjoy..!!!


/**
*Copyright (C) 2010  Jovial Java admin [email: jovialjava.blogspot@gmail.com]
*
*This program is free software: you can redistribute it and/or modify
*it under the terms of the GNU General Public License as published by
*the Free Software Foundation, version 3 of the License.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program.  If not, see .
*@author JovialJava
*/
package com.jovialjava.blog.utils;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeAsPerLocale {
 
 private static long NEW_YORK_OFFSET = -5L*60L*60L*1000L;
 private static long SINGAPORE_OFFSET = 8L*60L*60L*1000L;
 private static long INDIA_OFFSET = (long)(5.5*(60L*60L*1000L));
 
 public static void main(String[] args) throws Exception {
  Date date = new Date();
  Calendar c = Calendar.getInstance( );
  c.setTime(date);
  /**
   * Getting the CURRENT LOCALE OFFSET from GMT
   */
  int offset = c.get(Calendar.ZONE_OFFSET);
  /**
   * Getting the GMT time
   */
  long GMTTime = date.getTime( ) - offset;
  /**
   * New York Time = GMT - 5
   */
  long newYorkTime = GMTTime + NEW_YORK_OFFSET;
  /**
   * Singapore Time = GMT + 8
   */
  long singaporeTime = GMTTime + SINGAPORE_OFFSET;
  /**
   * India Time = GMT + 5.5
   */
  long indiaTime = GMTTime + INDIA_OFFSET;
  
  /**
   * Display and formatting
   */
  DateFormat df = DateFormat.getInstance( );
  System.out.println("GMT Time    : " + df.format(new Date(GMTTime)));
  System.out.println("New York Time   : " + df.format(new Date(newYorkTime)));
  System.out.println("Singapore Time   :"  + df.format(new Date(singaporeTime)));
  System.out.println("India Time    : " + df.format(new Date(indiaTime)));

  }
}