Android TimePicker 12 hour format - android

I have TimePicker in my Registration class to ask the user for their free time each day but it display the time in 24 hour format and I don't know how to view the time in a 12 hour format
I'm getting the value of TimePicker using
int hour = timepicker.getCurrentHour();
int min = timepicker.getCurrentMinute();
String time = hour + ":" + min;
and I also want to get the value of AM/PM

int hour = timepicker.getCurrentHour();
int min = timepicker.getCurrentMinute();
String state = "am";
if(hour > 12){
hour -=12;
state = "pm";
}
String time = hour + ":" + min + ":" + state;
PS: if you want the view itself show the time in 12-hours format you can add timepicker.setIs24HourView(false);

Related

How to get current hour in android?

Time class is no longer possible to use.
I want to ask you, how to detect in app 3-4am?
I need that to set up for example night mode in my app.
Can you give me some example how to do it?
Instead of using Time (because Time class was deprecated in API level 22.) you can use Calendar for getting current hour
val rightNow = Calendar.getInstance()
val currentHourIn24Format: Int =rightNow.get(Calendar.HOUR_OF_DAY) // return the hour in 24 hrs format (ranging from 0-23)
val currentHourIn12Format: Int = rightNow.get(Calendar.HOUR) // return the hour in 12 hrs format (ranging from 0-11)
We can use the Calendar class to get a format like "HH:mm:ss"
Calendar calendar = Calendar.getInstance();
int hour24hrs = calendar.get(Calendar.HOUR_OF_DAY);
int hour12hrs = calendar.get(Calendar.HOUR);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
System.out.println("Current hour 24hrs format: " + hour24hrs + ":" + minutes +":"+ seconds);
System.out.println("Current hour 12hrs format: " + hour12hrs + ":" + minutes +":"+ seconds);
Other option using the Date class and applying the format "HH:mm:ss":
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
String dateformatted = dateFormat.format(date);
System.out.println(dateformatted);
You can use following methods:
SimpleDateFormat format = new SimpleDateFormat("HH", Locale.US);
String hour = format.format(new Date());
Calendar calendar = Calendar.getInstance();
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);

Convert Received date time to local timezone time Android

Good day.I am building an chat application.For purpose i decided to put a date of message had been sent.No wounder that in different countries the date must show different.For example let's take 2 different countries and assume the difference between them are 2 hours.CountryX and CountryY.The user send message from CountryX which time is lets say 15:00.I am saving this on server with exact timezone time as user sent,exactly 15:00 as CountryX.Second user receives the message in CountryY which is more in 2 hours from CountryX,so basically The time which I MUST show in CountryY must be 17:00.This is the issue.How can i convert an already received time with known timezone to local in order to show correct?I did google a lot but all i came up,were solutions where you would simply just get an time for exact country,and not convert the CountryX sent Time to CountryY local time to show it correctly in CountryY.Please can you provide an help?Thank you very much beforehand.
For everyone suffering because of this.I have ended up creating my own class with my own logic and it works flawlessly and as an extra bonus couple of handy methods with time
public class Time {
public static String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String finalFormat = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
if (month < 10) {
String finalMonth = "0" + month;
finalFormat = year + "-" + finalMonth + "-" + day + " " + hour + ":" + minute + ":" + second;
}
return finalFormat;
}
public static String convertToLocalTime(String timeToConvert) {
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sourceFormat.setTimeZone(TimeZone.getTimeZone(Constants.SERVER_TIME_ZONE));//where server time zone is the time zone of your server as defauul,E.X -America/Los_Angeles
Date parsed;
try {
parsed = sourceFormat.parse(timeToConvert);
} catch (ParseException e) {
e.printStackTrace();
return "";
}
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
destFormat.setTimeZone(tz);
String result = destFormat.format(parsed);
return result;
}
public static String getTimeZone() {
return TimeZone.getDefault().getID();
}
}

Android Phone Silent on Time Comparison

all my code is in timer and it tik every 2 seconds
I have 3 different times
1) Time from the time picker(sTime).
2) Get Current time of my phone(cTime).
3) Expiry Time - (for creating range between timepicker's time and expiry time) (rTime).
I want to silent my phone when cTime is equal or after sTime
and turn back my phone profile to normal when cTime is equal or after rTime
but i cannot achieve this. i have done my coding and i think logic is fine but why its not working. please help me in this regard.
Here is my code
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String savedTime = sHour + ":" + sMin;
Date sTime = sdf.parse(savedTime);
Calendar c = Calendar.getInstance();
int currentHour = c.get(Calendar.HOUR);
int currentMin = c.get(Calendar.MINUTE);
String currentTime = currentHour + ":" + currentMin;
Date cTime = sdf.parse(currentTime);
int rangeHour = sHour;
int rangeMin = sMin + 1;
Date rTime = sdf.parse(rangeHour + ":" + rangeMin);
if (cTime.after(sTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Log.e("res", "Silent Mode Timing");
}
if (cTime.after(rTime)) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.e("res", "Normal Mode Timing");
}
} catch (Exception ex) {
Log.e("res", ex.toString());
}
Ok, I have a suggestion. The method 'after' of Date class compare two long values in milliseconds. When you get current time milliseconds value it calculate as current year + current month + current day and hour etc. (or something like this). And when you get milliseconds of you savedTime it calculates incorrect because you not specify full Date (year, etc). I mean that you startTime incorrect when it convert in long milliseconds value in Date.after method. try to change you algorithm to work wit long timestamp, not with Date. for example current time is System.currentTimeMillis(). I hope it help. Sorry for my English
Ok, try to use something like this:
private void compareTime(final String year, final String day, final String hour, final String month, final String minutes) {
AudioManager am;
am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
final SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:dd:mm:yy");
final String savedTimeValue = hour + ":" + minutes + ":" + day + ":" + month + ":" + year;
try {
final Date savedDate = sdf.parse(savedTimeValue);
final long savedTime = savedDate.getTime();
final long currentTime = System.currentTimeMillis();
final long rangeTimeMilliseconds = 1 * 60 * 1000; // 1 minute in milliseconds
if (currentTime > savedTime) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
if (currentTime > rangeTimeMilliseconds) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}catch(Exception e) {
e.printStackTrace();
}
}

How do I set AM/PM in a TimePicker?

I am using a TimePicker in my app. Whenever the user opens the screen with the TimePicker, I initialize it with the current time. When I do this, the TimePicker shows AM instead of PM. Why does this happen? Is there anything I have to add in my code?
Date initDate = m_NoteManageObject.getDateTimeArray(position);
Calendar myCal = Calendar.getInstance();
myCal.setTime(initDate);
TimePicker timePicker = (TimePicker)layout.findViewById(R.id.time_picker);
// Initialise Time Picker
timePicker.setCurrentHour(myCal.get(Calendar.HOUR));
timePicker.setCurrentMinute(myCal.get(Calendar.MINUTE));
You'll have to use Calendar.HOUR_OF_DAY instead of Calendar.HOUR.
i.e., timePicker.setCurrentHour() always expects the argument in 24-hour format. Unfortunately, this fact is not documented properly in the API documentation.
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute) {
if(hourOfDay>=0 && hourOfDay<12){
time = hourOfDay + " : " + minute + " AM";
} else {
if(hourOfDay == 12){
time = hourOfDay + " : " + minute + "PM";
} else{
hourOfDay = hourOfDay -12;
time = hourOfDay + " : " + minute + "PM";
}
}
deliveryTime.setText(time);
}
I think you have to override the onTimeSet() method of the Timepicker. Check this link
TimePickerDialog and AM or PM
May it helps you..
First, get an instance of the Calendar class, then use HOUR_OF_DAY to get the hour. HOUR_OF_DAY will be in 24-hour format so just assign that to a variable and then check whether that int is greater than 0 and less than 12. If this condition is true then append AM or else PM. Because HOUR_OF_DAY is 24-hour format, the PM hours will be displayed as 13,14 so to handle this, just subtract the HOUR_OF_DAY by 12. Here is the code:
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 12 && hour >= 0) {
tv.setText(hour + " AM");
} else {
hour -= 12;
if(hour == 0) {
hour = 12;
}
tv.setText(hour + " PM");
}
Try this :
Calendar calendar = Calendar.getInstance();
calendar.set(0, 0, 0, hourOfDay, minute, 0);
long timeInMillis = calendar.getTimeInMillis();
java.text.DateFormat dateFormatter = new SimpleDateFormat("hh:mm a");
Date date = new Date();
date.setTime(timeInMillis);
time.setText(dateFormatter.format(date));

Android + AM PM in a Time Object?

I'm setting a Time Object in Android. How do I set the AM and PM value at creation without relying on 24 hour time? For instance:
int hour = 7; // this returns 7am
//int hour = 19; this returns 7pm
myTime.set(second, minute, hour, day, month, year);
Log.i("TIME", "My time is: " + myTime);
It's not really clear what you're trying to do, but I suspect you want something like:
// Assume input of hour12 in range [1, 12] and isPM is a boolean
int hour24 = (hour12 % 12) + isPM ? 12 : 0;
That's assuming you want an hour of "12" and "AM" to mean midnight.
Then use hour24 when setting myTime.

Categories

Resources