I assume the timestamp is in UTC, and the offset is the UTC offset of the desired local time. If the timestamp is at a given offset from UTC, you will have to generate it a little differently.
A reliable way to generate this in Java would be to use the Joda-Time library, which is much better than the default java.util.Date
and java.util.Calendar
.
// A formatter that prints the timezone offset DateTimeFormatter fmt = DateTimeFormat.forPattern("Z"); // The current date+time in the system default timezone. DateTime dt = new DateTime(); // Create the result. String result = "/Date(" + dt.getMillis() + fmt.print(dt) + ")/";
It is a little annoying that DateTimeFormat
not able to output milliseconds from an era; this is what dt.getMillis()
concatenation requires.
To generate the same using java.util
classes would look something like this:
// A formatter that prints the timezone offset SimpleDateFormat df = new SimpleDateFormat("Z"); // Current date+time in system default timezone. Calendar now = Calendar.getInstance(); // Don't forget this if you use a timezone other than system default: df.setTimeZone( now.getTimeZone() ); // Create the result String result = "/Date(" now.getTimeInMillis() + df.format(now.getTime()) +")/";
This is essentially the same as the Joda-Time example, but the bit in which you need to copy the time zone from the calendar to the date format is the main source of errors.
Barend
source share