Java Date timezone conversion

First method to convert from Date to UTC string

  private String dateToUtcString(Date convert){
	    Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
	    now.setTime(convert);
	    try {
	      return DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) now).toString();
	    } catch (DatatypeConfigurationException e) {
	      throw new RuntimeException(e);
	    }
	  }

Second method assume/force set passed in date as UTC, then convert to PST timezone

private String dateToPstString(Date convert) {
		String value = convert.toString();

		DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		df1.setTimeZone(TimeZone.getTimeZone("UTC"));

		// Parses the value and assumes it represents a date and time in the EST
		// timezone
		try {
			Date utcDate = df1.parse(value);// database result is UTC time
			Calendar pstDate = Calendar.getInstance(TimeZone
					.getTimeZone("GMT-8:00"));// always -8, as CART hardcoded
												// +17
			pstDate.setTime(utcDate);

			return DatatypeFactory.newInstance()
					.newXMLGregorianCalendar((GregorianCalendar) pstDate)
					.toString();
		} catch (DatatypeConfigurationException e) {
			throw new RuntimeException(e);

		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return value;
	}
Advertisements

Author: lwpro2

Java J2EE professional

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s