fork download
  1. import java.text.SimpleDateFormat;
  2. import java.util.Calendar;
  3. import java.util.Date;
  4. import java.util.TimeZone;
  5.  
  6. public class Main {
  7.  
  8. /**
  9. * Utility function to convert java Date to TimeZone format
  10. * @param date
  11. * @param format
  12. * @param timeZone
  13. * @return
  14. */
  15. public static String formatDateToString(Date date, String format,
  16. String timeZone) {
  17. // null check
  18. if (date == null) return null;
  19. // create SimpleDateFormat object with input format
  20. // default system timezone if passed null or empty
  21. if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
  22. timeZone = Calendar.getInstance().getTimeZone().getID();
  23. }
  24. // set timezone to SimpleDateFormat
  25. sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
  26. // return Date in required format with timezone as String
  27. return sdf.format(date);
  28. }
  29.  
  30. public static void main(String[] args) {
  31. //Test formatDateToString method
  32. Date date = new Date();
  33. System.out.println("Default Date:"+date.toString());
  34. System.out.println("System Date: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", null));
  35. System.out.println("System Date in PST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "PST"));
  36. System.out.println("System Date in IST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "IST"));
  37. System.out.println("System Date in GMT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "GMT"));
  38. }
  39.  
  40. }
Success #stdin #stdout 0.29s 59876KB
stdin
Standard input is empty
stdout
Default Date:Wed Apr 24 12:55:02 GMT 2024
System Date: 24 Apr 2024 12:55:02 PM
System Date in PST: 24 Apr 2024 05:55:02 AM
System Date in IST: 24 Apr 2024 06:25:02 PM
System Date in GMT: 24 Apr 2024 12:55:02 PM