Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get the current date and the timezone in numbers format

I want to print the current date in this format 2017/06/05 > Year/Month/Day and next to it, the current timezone in this format +3

I used this code

String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

like image 872
Alaa AbuZarifa Avatar asked Jan 27 '26 10:01

Alaa AbuZarifa


1 Answers

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd | X");
System.out.println(sdf.format(new Date()));

gets close, but the time zone is printed with a leading zero:

2017/06/05 | +03

I suppose you could remove leading zeros from the time zone, if you need to:

SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat zone = new SimpleDateFormat("ZZZZZ"); // = +03:00
String tz = zone.format(new Date()).split(":")[0]
    .replaceAll("^(\\+|-)0", "$1"); // = +3
System.out.println(sdf.format(new Date()) + " | " + tz);

which gives:

2017/06/05 | +3
like image 107
David Conrad Avatar answered Jan 28 '26 23:01

David Conrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!