-1

In my application I am getting time value from the server in GMT format(YYYY-MM-DD hr-min-sec GMT) but I want to display in IST format (Aug-DD-YYYY hr-min-sec IST). How to do it programmatically?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Baskar P
  • 79
  • 1
  • 2
  • 11

1 Answers1

0

We will use SimpleDateFormat class to format the Date in specific format and we will set it’s timezone to print the date in specific timezone.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateFormatter {

    /**
     * Utility function to convert java Date to TimeZone format
     * @param date
     * @param format
     * @param timeZone
     * @return
     */
    public static String formatDateToString(Date date, String format,
            String timeZone) {
        // null check
        if (date == null) return null;
        // create SimpleDateFormat object with input format
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        // default system timezone if passed null or empty
        if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
            timeZone = Calendar.getInstance().getTimeZone().getID();
        }
        // set timezone to SimpleDateFormat
        sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
        // return Date in required format with timezone as String
        return sdf.format(date);
    }

    public static void main(String[] args) {
        //Test formatDateToString method
        Date date = new Date();
        System.out.println("Default Date:"+date.toString());
        System.out.println("System Date: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", null));
        System.out.println("System Date in PST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "PST"));
        System.out.println("System Date in IST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "IST"));
        System.out.println("System Date in GMT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "GMT"));
    }

}

Here is the output of the program:

Default Date:Wed Nov 14 21:37:01 PST 2012
System Date: 14 Nov 2012 09:37:01 PM
System Date in PST: 14 Nov 2012 09:37:01 PM
System Date in IST: 15 Nov 2012 11:07:01 AM
System Date in GMT: 15 Nov 2012 05:37:01 AM
Riyaz Parasara
  • 154
  • 8
  • 20