Search code examples
javatimezonesimpledateformatiso8601dataformat

an elegant way to transfer current date time into ISO 8601 format


i need a to transfer the current date time into ios8601 format, something like :

date and time in format: 01 Jan 2014 BST 12:00 PM

eventually on my jsp , i wish to put the formated date in

<time datetime="{date and time in ISO8601}">{date and time in format: 01 Jan 2014 BST 12:00 PM}</time>

my current try out:

    TimeZone tz = TimeZone.getTimeZone("BST");
    DateFormat df = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm'Z'");
    df.setTimeZone(tz);
    String nowAsISO = df.format(new Date());

but the result doesnt look like what i expect to get......


Solution

  • This pattern will give you what you need:

    SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy zzz HH:mm a");
    format.setTimeZone(TimeZone.getTimeZone("Europe/London"));
    System.out.println(format.format(new Date()));
    

    Prints:

    01 Sep 2014 BST 15:37 PM

    Note: I've assumed you were looking for BST = British Summer Time, which should be expressed as above. If you wanted Bangladesh time, use Asia/Dhaka as the timezone designator. Also note that British Summer Time is not in effect on 1st January (as quoted in your example).