Monday, July 1, 2013

Calculate UTC in Android

Hello Readers,

After A long Time I am restart My Blogging and add one more Tutorial about UTC.
OK first we have to know about utc and how it works. for That you have to visit the following page 
about UTC 

Now We Move to Android Side and see that how android calculate UTC.

first of all I assume that u have A basic Knowledge of Android Programming , Eclipse and all its related Stuff.

And Below you see the some images of final out put of your application.



and Related Code I pasted below




  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package com.example.utctime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	static final String DATEFORMAT = "yyyy-MM-dd HH:mm";
	private EditText mDateDisplay;
	private Button calImage;
	private int mYear;
	private int mMonth;
	private int mDay;
	private Spinner hhSpinner, mmSpinner;
	private EditText etUtc;
	private Spinner spTimeZone;
	private static final int DATE_DIALOG_ID = 1;
	private String selectedZone;
	private String selectedHours;
	private String selectedMinute;
	private String selectedDate;
	private Date date1 = null;

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

		mDateDisplay = (EditText) findViewById(R.id.etDateTime);
		etUtc = (EditText) findViewById(R.id.etUtc);
		calImage = (Button) findViewById(R.id.imgCal);

		calImage.setOnClickListener(this);

		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		spTimeZone = (Spinner) findViewById(R.id.spTimeZone);
		hhSpinner = (Spinner) findViewById(R.id.spHH);
		hhSpinner.setOnItemSelectedListener(new hhItemSelectedListener());
		hhSpinner.requestFocus();

		mmSpinner = (Spinner) findViewById(R.id.spMM);
		mmSpinner.setOnItemSelectedListener(new mmItemSelectedListener());
		mmSpinner.requestFocus();

		String[] TZ = TimeZone.getAvailableIDs();
		TZ[0] = "Select Time Zone";
		ArrayAdapter<String> Timeadapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, TZ);

		Timeadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		// ArrayList<String> TZ1 = new ArrayList<String>();
		// for (int i = 0; i < TZ.length; i++) {
		// if (!(TZ1.contains(TimeZone.getTimeZone(TZ[i]).getDisplayName()))) {
		// TZ1.add(TimeZone.getTimeZone(TZ[i]).getDisplayName());
		// }
		// }
		// TZ1.add(0, "Select Time Zone");
		// for (int i = 0; i < TZ1.size(); i++) {
		// Timeadapter.add(TZ1.get(i));
		// }

		spTimeZone.setAdapter(Timeadapter);
		spTimeZone
				.setOnItemSelectedListener(new timeZoneItemSelectedListener());
		spTimeZone.requestFocus();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imgCal:
			showDialog(DATE_DIALOG_ID);
			break;

		default:
			break;
		}
	}

	// create date Dialog
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {

		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	private void updateDisplay() {
		mDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mYear).append("-").append(mMonth + 1).append("-")
				.append(mDay).append(" "));
		selectedDate = mDateDisplay.getText().toString();

	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	// Hours Spinner

	public class hhItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedHours = parent.getItemAtPosition(pos).toString();
			// showToast(selected);
		}

		public void onNothingSelected(AdapterView parent) {
		}

	}

	// minute spinner
	public class mmItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedMinute = parent.getItemAtPosition(pos).toString();
			// showToast(selected);

		}

		public void onNothingSelected(AdapterView parent) {
		}
	}

	// minute spinner
	public class timeZoneItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			selectedZone = parent.getItemAtPosition(pos).toString();
			if (selectedHours.equalsIgnoreCase("hh")
					|| selectedMinute.equalsIgnoreCase("mm")
					|| selectedZone.equalsIgnoreCase("Select Time Zone")) {
				System.out.println("Please Select time and date and time zone");
			} else {
				String dateTime = selectedDate + selectedHours + ":"
						+ selectedMinute;
				System.out.println("old Date time - " + dateTime);

				String startTime = dateTime;
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm");

				try {
					date1 = dateFormat.parse(startTime);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("Formatted Date time - " + date1);
				date1 = GetUTCdatetimeAsDate();

				// String utcDate = GetUTCdatetimeAsString();

				System.out.println("UTC DATE  => " + date1);

				etUtc.setText(date1.toString());
			}

		}

		public void onNothingSelected(AdapterView parent) {
		}
	}

	public Date GetUTCdatetimeAsDate() {
		// note: doesn't check for null
		return StringDateToDate(GetUTCdatetimeAsString());
	}

	public String GetUTCdatetimeAsString() {
		final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
		if (selectedZone.equalsIgnoreCase("Select Time Zone")) {
			System.out.println("Selecte Time Zone Please");
			Toast.makeText(MainActivity.this, "Selecte Time Zone Please", Toast.LENGTH_LONG).show();
		} else {
			sdf.setTimeZone(TimeZone.getTimeZone(selectedZone));
		}
		final String utcTime = sdf.format(date1);

		return utcTime;

	}

	public Date StringDateToDate(String StrDate) {
		Date dateToReturn = null;
		SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

		try {
			dateToReturn = (Date) dateFormat.parse(StrDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return dateToReturn;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
In Above Code Line number 69 is important
- Timezone : Most applications will use getDefault() which returns a TimeZone based on the time zone where the program is running.
- TimeZone.getAvailableIDs Returns the system's installed time zone IDs. Any of these IDs can be passed to getTimeZone(String) to lookup the corresponding time zone instance.

If you wish to download complete source code. you can download from below link
UTC Calculator


1 comment:

  1. can you send file source code to addess mail :buibinh1989@gmail.com
    thanks!

    ReplyDelete