0

regarding my question above, I want to get current date time based on time zone (Kuala Lumpur). Can I know how to do?

Below is my current code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnTime = findViewById(R.id.btnTime);
    tvTime = findViewById(R.id.tvTime);

    btnTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",  Locale.getDefault());

            String time = "Current time - " + format.format(calendar.getTime());

            tvTime.setText(time);
        }
    });

}
  • 5
    Does this answer your question? [Get current time in a given timezone : android](https://stackoverflow.com/questions/16202956/get-current-time-in-a-given-timezone-android) – diogenesgg Dec 28 '19 at 04:26
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Dec 29 '19 at 07:21
  • Does your code give you what you want? What was the question again, please? If there’s any trouble with your code, please specify precisely how observed result differs from current date time in Kuala Lumpur. – Ole V.V. Dec 29 '19 at 07:21

1 Answers1

1

Malaysia observes GMT+8, and you can set the TimeZone of your SimpleDateFormat like

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
String time = "Current time - " + format.format(calendar.getTime());

Or, better, switch to the ThreeTenABP backport of java.time like

ZonedDateTime klDateTime = LocalDateTime.now().atZone(ZoneId.of("Asia/Kuala_Lumpur"));
String time = "Current time - " + klDateTime.format(DateTimeFormatter
        .ofPattern("yyyy-MM-dd HH:mm:ss"));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • the first one is better. Thanks mate – Radamel Falcao Dec 28 '19 at 04:08
  • 1
    Opinions differ. IMHO the first one is clearly inferior. The classes `SimpleDateFormat`, `TimeZone` and `Date` are all poorly designed and all long outdated. Also `Asia/Kuala_Lumpur` is correct while `GMT+08:00` may be correct today and may be incorrect for historic and/or future dates. – Ole V.V. Dec 29 '19 at 07:33
  • On the other hand the second one is incorrect. I just got `Current time - 2019-12-29 09:30:49`, but the time in Kuala Lumpur is 16:30. It shouldn’t be hard to fix, though. – Ole V.V. Dec 29 '19 at 08:31