I am using android.text.format.Dateformat package. For same locale, I am getting two different date formats. For example, US - 7/21/2017 and in another device as 7/21/17. First device is with API 18 and second one is API 24.
Different JRE implementations can have variations in how classes are implemented, even across versions. Your two devices likely have small variations in the default US date format, as in 2 vs 4 digits years.
You need to provide some code and JRE details if you want further guidance.
android.text.format.Dateformat will print strings that take into account the preferences set in the user's settings app. Almost every phone will allow you to choose between 12-hour and 24-hour time (e.g. 3:00 PM vs 15:00), but some phones also allow you to choose the format you'd like to see dates in.
I suspect your first phone's setting is M/d/yyyy and your second phone's is M/d/yy.
Related
I am developing an Android app for an Ethiopian company and have to deal with dates.
The calendar used in Ethiopia is similar to the Gregorian one but has two main differences: it's set approx. 7 years earlier and has 13 months.
At the time I post this question the date is 13-09-2021 in the Gregorian calendar and 03-01-2014 in the Ethiopian one.
My questions are:
does Android support the Ethiopian calendar and is it customary for people in Ethiopia to have their devices use it?
if so, do I have to get the default formatter (that uses the default calendar: Calendar.getInstance()) in order to format the date properly?
instead, if the device uses the Gregorian calendar how does Java support the translation to the Ethiopian date?
What would you suggest in order to simulate the full scenario, with the device set with the proper current Ethiopian date (as if coming from the network provider) and locale?
While I know nothing about these calendaring systems, perhaps…
ThreeTen-Extra
Add the ThreeTen-Extra library to your project to access the EthiopicChronology class that plugs into the java.time framework bundled with Android.
This chronology defines the rules of the Ethiopic calendar system. This calendar system is primarily used in Ethiopia. Dates are aligned such that 0001-01-01 (Ethiopic) is 0284-08-29 (ISO).
You can also find a CopticChronology class there too.
About the calendrical background:
The Ethiopian calendar is rather a local calendar with some popularity in Ethiopia itself. And yes, there is even a special time keeping mode in this country starting the day at 6 am. However, I am not sure if the calendar is also wide-spread on mobile phones due to lack of sufficient support in the common operating systems like Android, IOS or Windows. Outside of Ethiopia, it is probably only relevant for religous minded Ethiopian people in the diaspora.
Support on Android:
You can find some support presented by the class EthiopicCalendar delivered by IBM. I strongly assume that Amharic numbers are supported (but am not completely sure). I am less confident about the support for 6 am as start of the day and counting as zero (relevant if you ask for the current date). IBM says (similar but not identical to the standard usage of Calendar.getInstance()):
EthiopicCalendar usually should be instantiated using
Calendar.getInstance(ULocale) passing in a ULocale with the tag
"#calendar=ethiopic".
The API of IBM offers a translation to the gregorian calendar and vice versa via the counted milliseconds since 1970-01-01T00:00Z. For formatting or parsing, use the dedicated formatter engine of IBM. Attention, it is not the standard formatting engine of Android. Of course, you have still to worry with strange features like counting the first month as number zero (instead of one).
Alternative library Time4A:
My library Time4A is also written for Android and is a sister project of the main lib Time4J. Both libs contain the classes EthiopianCalendar and EthiopianTime. You will find some code examples in the javadoc. Support for non-decimal Amharic numbers exists, too. These classes require a special formatting engine, too, called ChronoFormatter. Like in case of IBM, Ethiopian month names like Meskerem (even in Amharic or other languages) are well supported.
A transformation to the gregorian calendar (and vice versa) can be obtained by the expression ethiopianDate.transform(PlainDate.axis()) where the parameter denotes the target calendar (here, PlainDate is the gregorian type).
I am looking for a way to print time-related strings like "Today" and "Yesterday" translated to the user's Locale (i.e language) in an Android app.
I have tried to use DateUtils.getRelativeDateTimeString but it
does not consider the locale, or at least it is not possible to change it during runtime. I would need something similar to this existing constructor of SimpleDateFormat:
public SimpleDateFormat(String pattern, Locale locale)
Of course, it would be possible to add translations of each word in every language but isn't there a better way assuming the words actually exists in the OS.
Is there a way to achieve this?
Edit:
I am trying to do something similar to the date picker on iOS:
With #Meno Hochschild' comment I was able to solve it by:
Adding the Time4A library.
Made a local copy of UnitPatterns.java and made it public.
Used it like this:
UnitPatterns.of(locale).getTodayWord(); // returns "today"
UnitPatterns.of(locale).getYesterdayWord(); // returns "yesterday"
This appears to be a translation problem,
not a date-format problem.
Your app will have messages that it wants to display to the user.
These messages will need to be translated into your target languages.
Once you know the message you want to display,
retrieve then display the localized (i.e. translated) message using the locale (Android supports that).
It is likely that you do you actually want to display the word "tomorrow" or "yesterday".
Instead,
you probably want to display something like "blah blah tomorrow" or
"sorry blah blah yesterday".
Translate the entire message,
not just the words individually.
Additional Info
I think you do need to translate "Today" into every target language.
And, you need to translate each of the date related strings into every target language (by which I mean "Tue May 1" needs to be translated into every language).
There are "tricks" you can use.
Choose the "base" part of the string and use placeholders for the other parts.
Placeholders,
because different languages may have different orders for
"Day-of-week Month Day"
I'm building a mega simple weather Android app using the forecast.io service.
Using the default call of
https://api.forecast.io/forecast/<my_key>/37.8136,144.9631?units=auto
Always seems to give me the forecast at a time that I don't care for - ie, its currently 2.40PM here, and it keeps giving me 3.40AM forecast.
So I then try to use the time param and yet it still gives me 3.40AM, not 2.40PM
https://api.forecast.io/forecast/<my_key>/37.8136,144.9631,1451619638?units=auto
I've validated 1451619638 as my current unix time via the helpful site http://www.epochconverter.com/
Any pointers as to why I can't seem to get MY local current time?
The API returns the timezone and then the offset from GMT. Check those.
The idea of the first one is if you do not provide the time, you will get a current forecast, and all you will have to do is convert it into your timezone. So if they are doing GMT and you are GMT - 8, you simply subtract 8 from the time value.
Both fields are there:
latitude: The requested latitude.
longitude: The requested longitude.
timezone: The IANA timezone name for the requested location (e.g. America/New_York). This is the timezone used for text forecast summaries and for determining the exact start time of daily data points. (Developers are advised to rely on local system settings rather than this value if at all possible: users may deliberately set an unusual timezone, and furthermore are likely to know what they actually want better than our timezone database does.)
offset: The current timezone offset in hours from GMT.
I have been using this API for a while.
I need to build a web service that analyzises SEO. The service will show how often the site was updated. I need to figure out how to get the posted date or update frequency from the HTML of the website.
For example on http://googletesting.blogspot.com/ I can get date from the tag <span>Wednesday, June 04, 2014</span>. Other websites don't use the same tags and date format so I can't us the same code to detect those dates.
(Dates can have very different formats in different locales. Also, month names can be written as text or as number. I need to match as much dates as possible.Sometime,date format isn't posted date but it's just words in articles.
My Algorithm about this
I attempt to get "posted date" from all posted then calculate update frequency.
Such as Fist posted at 30May 2012, Second posted at 29May2012, Third posted at 28May2012
So I will get result that this website was updated dairly
In the end, I want to know if each website updates:
Yearly
Monthly
Weekly
Daily
How do I reliably get this from any website?
Instead of parsing the dates in the page, you could download the home page and store it. Then you could come back every day and download the homepage again to see if it changed. This approach would work even for sites that don't publish any dates on their homepage. It would take longer to get your answer though.
Another approach would be to download the RSS feed for the site if it has one. The example site you give one has an XML feed: http://feeds.feedburner.com/blogspot/RLXA?format=xml RSS feeds are meant to be machine readable and the dates are in a consistent format.
You also say that you are using Java. I've found that Java's date parsing libraries are not very flexible. They force you to know the exact format of the date before you parse it. I have written a free, open source flexible date time parser in Java that you could try: http://ostermiller.org/utils/DateTimeParse.html Once you found dates on the page (maybe for looking at what comes after "posted on"), you could use my flexible parser to parse dates in a variety of formats.
I'm developing an android application and hit the problem with determining system first boot up time. I mean i need to measure how much time already passed from device first boot up.
I know about solution with listening for ACTION_BOOT_COMPLETED and save anything in SharedPreferences, but i need another solution, because this one does not work for some cases. Maybe there is any system property?
Use case (excerpt from discussion)
The filename of each file I receive from server includes a timestamp
taken from System.currentMillis()
I compare those timestamps in order to determine, which file the most current one is.
Now, the user changes system time a few months ahead.
I am still able to determine the most current file downloaded after user changed system time.
Now, the user changes time back to original setting.
The file downloaded on step 4 always wins when comparing timestamps.
The silver bullet to solve this problem would be a timestamp that counts seconds since first boot (after factory reset). Just like SystemClock.elapsedRealtime() but without reset after each boot. Unfortunately, the answers so far tell us, that this silver bullet doesn't exist.
However, many answers show a great variety of options how to tackle that problem. OneWorld123 commented each answer, how that suited his needs.
Maybe there is any system property?
Not sure about system property, but there is SystemClock class which provides API's to get system uptime:
SystemClock.uptimeMillis() which
Returns milliseconds since boot, not counting time spent in deep sleep.
You may also use SystemClock.elapsedRealtime() which
Returns milliseconds since boot, including time spent in sleep.
Hope this helps.
In case one needs to know when was the first time an Android device was booted,
The easiest method would be to have an application
that is installed in the factory image
that is configured to run during boot
that logs the current date & time into a sharedPreference on its first run
Subsequently any other apps that need to determine the first boot time of the Android device can lookup the appropriate sharedPreference during the lifetime of the device. (or until the device is factory-reset; at which point the pre-installed app would write the new date&time into the shared preference after a reboot.)
However if it is not possible to an pre-install an application on the Android device, then a couple of potential workarounds would be:
1. As a root/superuser
one would lookup the time-stamp of a directory/file that is known to get created on the Android device during first-boot.
2. As a regular app,
a simple workaround method using standard Android APIs would be to check for the installation-time of an appropriate system package that is known to get installed during first-boot.
/* This returns the last time a package was installed */
PackageManager pm = context.getPackageManager();
PackageInfo pInfo = pm.getPackageInfo(<app-package-name>, 0);
return pInfo.firstInstallTime;
3. Alternately as a regular app,
if we can rely on a specific package being updated one-time during first-boot (and never again) we can check its update-time as follows:
/* This returns the last time a package was updated */
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(<app-package-name>, 0);
String appFile = appInfo.sourceDir;
long installed = new File(appFile).lastModified();
If we stick to the SDK, I don't know of a method providing this information directly; but there might be a way to derive this information from other resources. Again, if we stick to SDK, one "rather reliable" option is to use application usage statistics which Android OS saves during device lifetime. That is - the timestamp for a first "usage stats" ever saved.
This, though, clearly does not provide an exact "first boot time" timestamp, so it depends on whether some approximation is OK in your case. Generally, the problem with usage statistics is that Andriod aggregates it for periods distant in time - so, the older device is - the less accurate the date is. For example, for my current phone, first booted on Dec. 3 2014, aggregated usage statistics is first recorded on Dec. 21 2014 currently (for the record - it is Feb. 2016 by the time of this writing). (I have to admit though that I don't know how Android OS schedules the aggregation, and if it is just scheduled on Dec. 21 every year, or if it is indeed somewhat close to the first device usage - I guess it is easy to check with any other device.)
Following is some sample code showing UsageStatsManager usage, but it certainly would need more adjustments in order to address the fact of having more precision for more recent periods:
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
Calendar year2013 = Calendar.getInstance(); year2013.set(2013, 0, 1);
List<UsageStats> stats = usageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_YEARLY, // or adjust for "younger" devices to get more precision - so, you'll probably need several queries
year2013.getTimeMillis(),
Calendar.getInstance().getTimeInMillis());
// now, first element in stats (if it is present at all) will point to the "earliest" statistics saved *for this interval* (yearly in this case)
// use UsageStats.getFirstTimeStamp() to get first known/saved usage
Note also that, as documented in the SDK, UsageStatsManager requires PACKAGE_USAGE_STATS system-level permission, so you'll need to make user accept it in Settings first:
Intent settingsIntent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(settingsIntent);
Hope it helps!
According to your discussion on: https://chat.stackoverflow.com/rooms/102325/discussion-between-ankitagrawal-and-oneworld , you need a monotonic counter to uniquely identify a dataset.
For that you can easily set a SharedPreference and increment this value every time you need a new identifier. When you require to know which is the newest file, just compare the identifiers. If it is an issue that this counter gets reset once the app is uninstalled, please refer to: In android is there any way to preserve SharedPreferences after an uninstall
A different approach that could be used, is to request a timestamp from an outside server.
Hope it helps ;-)
There are 3 methods in ANDROID SDK for these:-
public static long elapsedRealtime ()
Added in API level 1
Returns milliseconds since boot, including time spent in sleep.
Returns
elapsed milliseconds since boot.
public static long elapsedRealtimeNanos ()
Added in API level 17
Returns nanoseconds since boot, including time spent in sleep. Returns
elapsed nanoseconds since boot.
For #oneWorld Case:
You can use 2 approach:-
1) While writing check if some data has date above the current date then change the date of previous data to something less than current data and time,
so it will return correct latest data.
2) You can store the time on server and retrieve time from there and set it.