I have an Android Watch Face that works for 12-hour formats. I am confused how to implement a 24-hour format based on the system preference of the phone, using TextClock or any other method.
SimpleDateFormat twelvehour = new SimpleDateFormat("h:mm a", Locale.US);
String TimeAmPmNoSec = String.format("%s", twelvehour.format(cal.getTime()));
canvas.drawText(TimeAmPmNoSec, (centerX - (timeXLength / 2.0f ), timeYOffset, timePaint);
That setting is bridged from your phone to the watch automatically and you can get it on your watch app by calling DateFormat.is24HourFormat(context).
Related
I was working on Time conversion from One Locale to another (US to Swedish) in android using Java. It is working well on all the devices except Samsung devices.
DateTimeFormatter parser = DateTimeFormatter.ofPattern("hh:mm a", Locale.US);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a", new Locale("sv","SE"));
LocalTime time = LocalTime.parse("06:45 AM", parser);
String formatted = time.format(formatter);
In other devices I am getting output as 06:45 FM
In samsung devices I am getting it as
06:45 AM itself.
I want the the output to show as 06:45 FM in every device type.
Note : This issue only occurs for Time conversion,Date conversion (month names) works fine.
Thanks in advance.
I am working on notifications and I need to display the time-> An action was performed in a way similar to ("5 seconds ago","12 mins ago","1 week ago" etc.)
This is the code I am using
long now = System.currentTimeMillis();
String datetime1 = "06/12/2015 03:58 PM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm aa");
Date convertedDate = dateFormat.parse(datetime1);
CharSequence relavetime1 = DateUtils.getRelativeTimeSpanString(
convertedDate.getTime(),
now,
DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
And the result I get is
relativetime1=June 12, 2015
The above obtained result doesn't seem like what its supposed to look like.
By searching online I've found that if that duration is greater than a week, in which case it returns an ABSOLUTE
-I don't quite understand what I found.
How do I achieve my requirement without using an external library?
Kindly help.
I have an Asus Fonepad first generation(android 4.1.2) and an Asus Fonepad second generation(android 4.3).
I use the following code to parse the date to the desired format in my app:
SimpleDateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss yyyy", /*new Locale("nl", "NL")*/Locale.GERMANY);
df.setTimeZone(TimeZone.getTimeZone(/*"Europe/Amsterdam"*/"Europe/Berlin"));
String time = df.format(new Date());
The above code results in "Dez 23 17:09:25 2013" on the first generation fonepad and "Dez. 23 17:09:25 2013" on the second generation fonepad.
As you can see, the second generation adds a dot after the month.
this causes a parsexception on the server side.
Why does SimpleDateFormat behave differently on different devices(android versions)? This is worrying.
Is there a way to always get the same format? What is the solution to this?
Thanks.
SimpleDateFormat (and some other framework classes) use icu4c library to format content. Month format for DE was changed between 49.2 and 50.1 versions of this library.
No, you can't expect same behavior for all android versions.
Link to sources: https://android.googlesource.com/platform/external/icu4c/+/android-4.4.2_r1/data/locales/de.txt
Add: If you sending data to a server than solution is to use only numbers: 12 will be always 12 for December.
I'm working on an android application, as part of me trying to learn android programming, that will switch audio profiles based on day and time (provided by the user)... So far I have got most of the layout done, I have also created a service that will run in the background to perform few checks...
Right now I'm having a hard time trying to find an elegant way to handle checking if current time falls in time range saved by the user... I'm saving the user's preference for time range in a string format from androids TimerPicker control, I need to check if the current time falls in the user saved times...
Right now I have the following code:
the 'from time' is coming in with the following: hour:minute:AM/PM -- 8:59:AM in string format
the 'to time' is coming in with the following: hour:minute:AM/PM -- 4:59:PM in string format
if(fromAMPM.equals("AM")){
from.set(from.AM_PM, from.AM);
} else {
from.set(from.AM_PM, from.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
from.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, fromHour, fromMinute);
if(toAMPM.equals("AM")){
to.set(to.AM_PM, to.AM);
}else{
to.set(to.AM_PM, to.PM);
}
//dont care about the YEAR and MONTH, so set it to current MONTH and YEAR
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
//this is just for me to see what got set:
SimpleDateFormat df3 = new SimpleDateFormat("HH:mm aaa");
String formattedDate1 = df3.format(from.getTime());
String formattedDate2 = df3.format(to.getTime());
After all this processing:
formattedDate1 is returning: 08:59 AM
formattedDate2 is returning: 04:59 AM
Any suggestions?
Thanks
Take a look at the Calendar documentation, under the section "Inconsistent Information"
http://developer.android.com/reference/java/util/Calendar.html
You call:
to.set(rightNow.get(rightNow.YEAR), rightNow.get(rightNow.MONTH), dayOfWeek, toHour, toMinute);
Which sends toHour as HOUR_OF_DAY (24h), not HOUR (12h).
It says that when you supply it with inconsistent information, it just uses the latest information. You're telling it that toHour is 4 on a 24hour scale, which is inconsistent with your PM setting, so it throws the PM setting away.
The easiest change would probably be just to add 12 to toHour instead of setting the AM_PM. Or, don't use the set(year, month, day, hourofday, minute) command and just set hour and am_pm separately.
I would like in my application to find a way to synch the date and time with something given by an external source.
I don't want to use the phone time because I might get a difference of maybe 5 minutes around real time. and 5 minutes extra or less = 10 minutes!
I have heard about time information in the GPS satellites or in Network antennas.
I have tried with System.getCurrentTime but i get the current the of the device, so, if my device is set up 5 minutes earlier, it display the wrong time.
EDIT
To make a short question: how can I get this time?
I didn't know, but found the question interesting. So I dug in the android code... Thanks open-source :)
The screen you show is DateTimeSettings. The checkbox "Use network-provided values" is associated to the shared preference String KEY_AUTO_TIME = "auto_time"; and also to Settings.System.AUTO_TIME
This settings is observed by an observed called mAutoTimeObserver in the 2 network ServiceStateTrackers:
GsmServiceStateTracker and CdmaServiceStateTracker.
Both implementations call a method called revertToNitz() when the settings becomes true.
Apparently NITZ is the equivalent of NTP in the carrier world.
Bottom line: You can set the time to the value provided by the carrier thanks to revertToNitz().
Unfortunately, I haven't found a mechanism to get the network time.
If you really need to do this, I'm afraid, you'll have to copy these ServiceStateTrackers implementations, catch the intent raised by the framework (I suppose), and add a getter to mSavedTime.
Get the library from http://commons.apache.org/net/download_net.cgi
//NTP server list: http://tf.nist.gov/tf-cgi/servers.cgi
public static final String TIME_SERVER = "time-a.nist.gov";
public static long getCurrentNetworkTime() {
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
//long returnTime = timeInfo.getReturnTime(); //local device time
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime(); //server time
Date time = new Date(returnTime);
Log.d(TAG, "Time from " + TIME_SERVER + ": " + time);
return returnTime;
}
getReturnTime() is same as System.currentTimeMillis().
getReceiveTimeStamp() or getTransmitTimeStamp() method should be used.
You can see the difference after setting system time to 1 hour ago.
local time :
System.currentTimeMillis()
timeInfo.getReturnTime()
timeInfo.getMessage().getOriginateTimeStamp().getTime()
NTP server time :
timeInfo.getMessage().getReceiveTimeStamp().getTime()
timeInfo.getMessage().getTransmitTimeStamp().getTime()
Try this snippet of code:
String timeSettings = android.provider.Settings.System.getString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME);
if (timeSettings.contentEquals("0")) {
android.provider.Settings.System.putString(
this.getContentResolver(),
android.provider.Settings.System.AUTO_TIME, "1");
}
Date now = new Date(System.currentTimeMillis());
Log.d("Date", now.toString());
Make sure to add permission in Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers.
Commonly this message is seen as GMM Info and contains the following informaiton:
Certain carriers dont support this and some support it and have it setup incorrectly.
LAYER 3 SIGNALING MESSAGE
Time: 9:38:49.800
GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)
M Protocol Discriminator (hex data: 8)
(0x8) Mobility Management message for GPRS services
M Skip Indicator (hex data: 0)
Value: 0
M Message Type (hex data: 21)
Message number: 33
O Network time zone (hex data: 4680)
Time Zone value: GMT+2:00
O Universal time and time zone (hex data: 47716070 70831580)
Year: 17
Month: 06
Day: 07
Hour: 07
Minute :38
Second: 51
Time zone value: GMT+2:00
O Network Daylight Saving Time (hex data: 490100)
Daylight Saving Time value: No adjustment
Layer 3 data:
08 21 46 80 47 71 60 70 70 83
15 80 49 01 00
This seemed to work for me:
LocationManager locMan = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
long networkTS = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();
Working on Android 2.2 API (Level 8)
Now you can get time for the current location but for this you have to set the system's persistent default time zone.setTimeZone(String timeZone) which can be get from
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
TimeZone current = calendar.getTimeZone();
setAutoTimeEnabled(boolean enabled)
Sets whether or not wall clock time should sync with automatic time updates from NTP.
TimeManager timeManager = TimeManager.getInstance();
// Use 24-hour time
timeManager.setTimeFormat(TimeManager.FORMAT_24);
// Set clock time to noon
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 12);
long timeStamp = calendar.getTimeInMillis();
timeManager.setTime(timeStamp);
I was looking for that type of answer I read your answer but didn't satisfied and it was bit old. I found the new solution and share it. :)
For more information visit: https://developer.android.com/things/reference/com/google/android/things/device/TimeManager.html
I read that this
LocationManager locMan = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
long time = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).getTime();
provides correct time, without internet at the cost of some blocking processing.
the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.
the gps signal does indeed include a precise time signal, which is available with any "fix".
however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.
note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?