简体   繁体   中英

How to add timezone to the timestamp?

I've a timestamp which print date and time(24 hours format)

String timeStamp = new SimpleDateFormat("ddMMMyyyyHHmm").format(Calendar.getInstance().getTime());

When I print timeStamp the output is

27Feb20180051

but I want something like this

27Feb20180051EST

Any idea how to proceed?

Try Following code,

SimpleDateFormat dateFormatter = new SimpleDateFormat("ddMMMyyyyHHmmz");
String timeStamp = dateFormatter.format(Calendar.getInstance().getTime());

You can format your date according to your requirement using patterns. More information is included in following link. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

试试下面的代码

String timeStamp = new SimpleDateFormat("ddMMMyyyyHHmmz").format(Calendar.getInstance().getTime());
    String timeStamp = ZonedDateTime.now(ZoneId.of("America/Panama"))
            .format(DateTimeFormatter.ofPattern("ddMMMuuuuHHmmzzz", Locale.ENGLISH));
    System.out.println(timeStamp);

This just printed

27Feb20180408EST

Messages:

  1. Specify explicit time zone. Please substitute your desired time zone if it didn't happen to be America/Panama. You may specify ZoneId.systemDefault() to use the JVM's time zone setting, only please be aware that this may be changed by other parts of your program or other programs running in the same JVM.
  2. Specify explicit locale. I took 'Feb' for English and suggested Locale.ENGLISH , your preference may differ. Also the time zone abbreviation may be different in different locales.
  3. Use java.time, the modern Java date and time API. Calendar , Date and SimpleDateFormat are long outdated and the last in particular notoriously troublesome, so I recommend you avoid them. The modern API is so much nicer to work with.
  4. Avoid the three and four letter time zone abbreviations if you can. While EST may(!) not be understood as something else than North American Eastern Standard Time (UTC-5), many, possibly most abbreviations are ambiguous and hence prone to be misinterpreted at the other end. A recommended format is ISO 8601, like 2018-02-27T04:08-05:00 . It's unambiguous, and since it's standard it will be widely understood. You can generate it easily in Java: OffsetDateTime.now(ZoneId.of("America/Panama")).toString() .

Link: Oracle tutorial: Date Time explaining how to use java.time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM