Skip to content
Permalink
Browse files

Converting the Date and Time

  • Loading branch information...
dragosholban committed Mar 10, 2018
1 parent 40e18d3 commit 75abba1f450df5cf0ad784d11b322a113c552dd5
Showing with 23 additions and 0 deletions.
  1. +23 −0 app/src/main/java/dragosholban/com/timezoneconverter/MainActivity.java
@@ -23,6 +23,8 @@
TimeZone userTimeZone;
String[] selectedTimezones = new String[] {"Europe/Bucharest", "Europe/London", "Europe/Paris"};
TimeZone selectedTimeZone;
TextView convertedTimeTv;
TextView convertedDateTv;

private static int CHOOSE_TIME_ZONE_REQUEST_CODE = 1;

@@ -33,6 +35,8 @@ protected void onCreate(Bundle savedInstanceState) {

SeekBar seekBar = findViewById(R.id.seekBar);
final TextView userTime = findViewById(R.id.userTime);
convertedTimeTv = findViewById(R.id.convertedTime);
convertedDateTv = findViewById(R.id.convertedDate);

seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
@@ -42,6 +46,7 @@ public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
if (fromUser) {
localDate.setMinutes(0);
}
convertDate(userTimeZone, selectedTimeZone);
}

@Override
@@ -68,6 +73,7 @@ public void onStopTrackingTouch(SeekBar seekBar) {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectedTimeZone = TimeZone.getTimeZone(selectedTimezones[i]);
convertDate(userTimeZone, selectedTimeZone);
}
});
}
@@ -86,6 +92,7 @@ public void setLocalDate(Date date) {
localDate.setMinutes(minutes);
Button dateBtn = findViewById(R.id.dateButton);
dateBtn.setText(DateFormat.getDateInstance().format(localDate));
convertDate(userTimeZone, selectedTimeZone);
}

public void chooseTimezone(View view) {
@@ -100,5 +107,21 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectTimeZoneBtn.setText(timezone);
userTimeZone = TimeZone.getTimeZone(timezone);
}
convertDate(userTimeZone, selectedTimeZone);
}

private void convertDate(TimeZone fromTimeZone, TimeZone toTimeZone) {
if (fromTimeZone != null && toTimeZone != null) {
long fromOffset = fromTimeZone.getOffset(localDate.getTime());
long toOffset = toTimeZone.getOffset(localDate.getTime());
long convertedTime = localDate.getTime() - (fromOffset - toOffset);
Date convertedDate = new Date(convertedTime);
int hours = convertedDate.getHours();
int minutes = convertedDate.getMinutes();
String time = (hours < 10 ? "0" + Integer.toString(hours) : Integer.toString(hours))
+ ":" + (minutes < 10 ? "0" + Integer.toString(minutes) : Integer.toString(minutes));
convertedTimeTv.setText(time);
convertedDateTv.setText(DateFormat.getDateInstance().format(convertedDate));
}
}
}

0 comments on commit 75abba1

Please sign in to comment.
You can’t perform that action at this time.