Convert String to Date format in andorid - android-studio

I am getting the strings like 1604341549 and want to convert them to normal date format like
12 feb 2012 4:00. Here is my implementation
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
try {
Date d = sdf.parse(date);
sdf.applyPattern("dd MMM yyyy hh:mm");
holder.v.setText(sdf.format(d));
} catch (ParseException ex) {
Log.e("Exception", ex.getLocalizedMessage());
}
I have checked the logs and it is showing the dates as String before the try block but it is not implementing in the try block instead it is giving an error " Unparseable date: "1604341549" ".

Looks like your date is a long that encodes timestamp in seconds so you don't need to parse a String, instead you should simply build a Date object using Date(long date) constructor. don't forget to convert seconds to milliseconds by multiplying it by 1000

java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare two formatters, one for your input and one for your desired output.
/** For parsing seconds since the epoch */
private static final DateTimeFormatter unixTimestampFormatter
= new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.toFormatter();
/** For formatting into normal date and time */
private static final DateTimeFormatter normalFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(Locale.UK);
Now the conversion goes like this:
String inputStr = "1604341549";
Instant inst = unixTimestampFormatter.parse(inputStr, Instant.FROM);
String normalDateTimeStr = inst.atZone(ZoneId.systemDefault())
.format(normalFormatter);
System.out.println(normalDateTimeStr);
Output is:
02-Nov-2020 19:25:49
I am convinced that Shamm is correct in the other answer: your input strings contain so-called Unix timestamps, that is, counts of seconds since the Unix epoch on Jan 1, 1970 at 00:00 UTC. With java.time we can build a formatter that parses such.
For giving “normal” output I am using Java’s built-in date and time format. In this case for UK locale, but you should use your users’ locale for most content users.
What went wrong in your code?
First, you were trying to parse the input string as containing year, month, date, hour, etc., which it didn’t. So you were lucky to get an exception so you got aware that it’s wrong (SimpleDateFormat very often does not give that, leaving you believing that everything is fine when it isn’t).
SimpleDateFormat parsed 1604 as year, 34 as month, 15 as day of month and 49 as hour of day. It then objected because there weren’t any digits left for the minutes (and seconds).
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Unix time
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Related

JAVA - Parse String date to long [duplicate]

This question already has answers here:
java.text.ParseException: Unparseable date Error on using Clock.systemUTC() [duplicate]
(2 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
2024-01-01T00:00:00.000Z
I would like to get this String in ms(long)
I tried:
long res = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(createdAt).getTime();
but it doesn't work.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
public class Main {
public static void main(String[] args) {
long res = Instant.parse("2024-01-01T00:00:00.000Z").toEpochMilli();
System.out.println(res);
}
}
Output:
1704067200000
ONLINE DEMO
Note that the modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
Learn more about the modern Date-Time API from Trail: Date Time.
For any reason, if you want to use SimpleDateFormat:
Use the following format:
yyyy-MM-dd'T'HH:mm:ss.SSSXXX
Check the SimpleDateFormat documentation to understand the difference between Z and X.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.

Issue of Reading and Converting Date of Google Calendar Events when language is set to Arabic in C#

I am Using Google APis .net client library to read calendar events.
I have following line of code
newRow["Start"] = pEventItem.Start.DateTime.HasValue ?
Convert.ToDateTime(pEventItem.Start.DateTime) : Convert.ToDateTime(pEventItem.Start.Date);
Where PEventItem is of type Google.Apis.Calendar.v3.Data.Event and NewRow[...] is of type DataRow. The Value of pEventItem.Start.Date is "2019-06-24" (as seen in debug window)
The above line of code works perfect, But fails when UI language / Culture is set to Arabic (SaudiArabia) The same Convert.ToDateTime throws error "String was not recognized as a valid DateTime".
btw, How i am changing the UI language is as below for your information.
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(ChangeLanguageTo);
Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(ChangeLanguageTo);
I tried to set 2nd parameter of the Convert.ToDateTime function in an hope that it will convert date correctly...
CultureInfo enUsCulture = new CultureInfo("en-us");
newRow["Start"] = pEventItem.Start.DateTime.HasValue ? Convert.ToDateTime(pEventItem.Start.DateTime, enUsCulture) : Convert.ToDateTime(pEventItem.Start.Date, enUsCulture);
Well Now it does not throw exception, but the returned date is incorrect. value retuned is {21/10/40 12:00:00 ص}
while The actual date pEventItem.Start.Date is "2019-06-24"
I also tried invariant culture also, but result is same, converted date is wrong. What could be the issue?
Regards
There are a few things going on here.
Firstly, if you use EventDateTime.DateTime (e.g. via pEventItem.Start.DateTime) you don't need to call Convert.ToDateTime, because that's already a DateTime?... you can just take the Value property to get a DateTime from a DateTime?. However, I should warn that that can perform time zone conversions that you may not want. (We can't fix the library to avoid those, as it would be a breaking change.) Instead, you may want to parse EventDateTime.DateTimeRaw, which is the original string value returned by the API.
When parsing, I'd suggest using the invariant culture using CultureInfo.InvariantCulture (instead of creating an en-US culture), and parse using DateTime.ParseExact, specifying the format you expect based on whether you're parsing a date or a full date/time.
In terms of "the returned date is incorrect" - I believe that's really just the formatted value that's using the default culture, including the calendar system. We can see that at play in the code below, which constructs the DateTime directly (so can't be affected by any text parsing etc). When formatted using the invariant culture, it shows as 2019-06-24, but when formatted with ar-SA, it shows as "1440-10-21" due to the default calendar system for that culture being System.Globalization.UmAlQuraCalendar:
// Note: when a calendar system is not specified,
// it's implicitly Gregorian.
DateTime date = new DateTime(2019, 6, 24);
Console.WriteLine(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
Console.WriteLine(date.ToString("yyyy-MM-dd", new CultureInfo("ar-SA")));
So what you're seeing in the debugger is the correct date - but formatted in a way you weren't expecting.

How can I convert a variant VT_DATE to a string and include the time at midnight

I currently convert dates from variant format to string using the VariantChangeType (or CComVariant::ChangeType). That works well, except when the time portion of the variant value is midnight. In that case, the time is simply omitted from the converted string.
A timestamp of 2015/10/07 03:40:00 is converted to a string just as you would expect: "10/7/2015 03:40:00 AM" (using my regional settings).
But a timetamp of 2015/1007 00:00:00 is converted to this string: "10/7/2015" (no time portion included).
I'm trying to preserve that midnight time, and keep the regional settings in use too. I've looked at _strftime_l() - it does include a time in the converted string, but doesn't appear to use the regional settings, even when one is provided via _get_current_locale().
I'm using C++ on Windows.
Has anyone done this?
OK - I found a way to resolve this. Windows has two API calls that will format the date and time with regional settings: GetDateFormat() and GetTimeFormat(). They each take a SYSTEMTIME structure, an output buffer, and a locale specifier. On return, the output buffer contains the date (or time) converted to a string matching the locale and regional settings in use.
I also found that _strftime_l() will actually use regional settings if you call setlocal(LC_ALL, "") first. I was a bit leery of using that method as it may have side affects I'm not aware of.

Strange sybase behavior around daylight savings time (DST)

I've got a strange sybase behavior which I do not understand.
Situation
I have a table (MY_TABLE) with several columns of type smalldatetime. For illustration purposes let's assume the following table and data:
MY_TABLE||ID |TS_INIT |TS_LASTCHANGE |MY_TEXT |
||4711|3/31/2013 12:00:00 AM|3/31/2013 3:00:00 AM|someText|
TS_INIT and TS_LASTCHANGE are of type smalldatetime.
When executing the following statement I get the above result:
SELECT ID, TS_INIT, TS_LASTCHANGE MY_TEXT
FROM MY_TABLE
WHERE ID = 4711
go
My client is running in UTC+1 (Berlin) and has daylight savings time (DST) enabled.
I am not sure in what time zone the server is running and whether or not DST is enabled.
Problem
When I execute this (note that it is 03:00h):
SELECT ID, TS_INIT, TS_LASTCHANGE MY_TEXT
FROM MY_TABLE
WHERE ID = 4711 AND TS_LASTCHANGE = "2013-03-31 03:00:00:000"
go
I get NO results but when I execute this (note that it is 02:00h this time):
SELECT ID, TS_INIT, TS_LASTCHANGE MY_TEXT
FROM MY_TABLE
WHERE ID = 4711 AND TS_LASTCHANGE = "2013-03-31 02:00:00:000"
go
I do again get the above result which is saying TS_LASTCHANGE is
3/31/2013 3:00:00 AM
Note that the result prints 03:00h, even though I queried for 02:00h.
Why Is the first query returning no results even though there should be a match and why is the second query returning a result even though there should be no match?!
Note also that 3/31/2013 3:00:00 AM is the first moment in DST (at least in the year 2013) and 3/31/2013 2:00:00 AM should never ever exist at all because when transitioning from winter to summer time, the clock switches from 01:59:59 to 03:00:00 (as per this site).
Database: Adaptive Server Enterprise V15.0.3
Client: Aqua Data Studio V16.0.5
EDIT:
When querying whit the TS_INIT everything works as one would expect (only a result for 3/31/2013 12:00:00 AM)
Aqua Data Studio is written in Java.
The problem you are having has to do with the fact that Java is aware of timezones and databases don't have a concept of timezone when they store date and times. When the time comes back from the database, the database's JDBC driver puts it in a Java date and just assumes the timezone is irrelevant. The problem happens when you try to display a time which the JVM thinks is invalid, so a valid date is presented, which basically pushes the time by an hour. Daylight savings for 2015 started on March 08 2.00 AM and one of your rows contains a date which is invalid according to JVM.
This has been a known design issue with Java, and they are trying to fix this with JSR-310 for inclusion in Java SE 8. With this, they will have LocalDate, OffsetDate and ZonedDate. You can read more about it here ...
https://today.java.net/pub/a/today/2008/09/18/jsr-310-new-java-date-time-api.html#jsr-310-datetime-concepts
https://jcp.org/en/jsr/detail?id=310
http://docs.google.com/View?id=dfn5297z_8d27fnf
Workaround
The only workaround, is to probably trick the JVM by setting the timezone in the JVM to GMT. If you are running ADS 16 on Windows, and you launch ADS with the shortcut icon on the desktop (which runs datastudio.exe), then you need to modify the datastudio.ini file in your folder. Add a new entry for vmarg.5=-Duser.timezone=gmt
This link explains the location of where to find the data studio.ini
https://www.aquaclusters.com/app/home/project/public/aquadatastudio/wikibook/Documentation14/page/50/Launcher-Memory-Configuration#windows
Once you have made the change, Restart ADS. Then go to Help->About->System: and double check your user.timezone setting and make sure it is GMT. Then give it a try.
With the above change there might be side effects in the application where timezone are involved, For e.g. in the Table Data Editor->Insert Current Date&Time, which would display a GMT time ... so there would be an offset.

Timezone format connections

I got the time values from the SBT SDK as a string in this format
"2013-07-17T14:44:25.177Z"
I get a Java Date object with this code
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = dateFormat.parse("2013-07-17T14:44:25.177Z");
But the last part of the string ".177Z" should be a time zone value !?!?!
Do any body know how parse the time zone or the complete date with the time zone in Java?
Thx
Andreas
But the last part of the string ".177Z" should be a time zone value !?!?!
No, I think the .177 is the milliseconds part, and Z is a UTC-offset of 0. (It's not really a time zone, but that's a different matter.)
I suspect you want:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
(Where X is an ISO-8601 time zone specifier, including Z for UTC.)
Note that X was only introduced in Java 7 - if you're using Java 6 or earlier, you may need to do a bit more work.
You might want to use
javax.xml.bind.DatatypeConverter.parseTime(String)
since the dates found in the atom returned by the IBM Connections API conform to the definition from http://www.w3.org/TR/xmlschema-2/, which can be parsed into a Java Calendar Object by said method. This also accounts for the time zone specifier.

Resources