I'm trying to create a Date from a String I receive from the server. The String is:
2018-05-23T06:39:37+0000
So the correct format should be:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
Here is my code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
I don't know if there is any way to do this, because after that I would like to parse again to the next format:
dd/MM/yyyy hh:mm
I've tried to parse the original String using this last format directly but I'm getting the same exception.
Any suggestion?
I see you've solved your own problem with a little help from the comments, however I would suggest you seriously consider LocalDate, as the older Date classes are quite troublesome at times.
In fact, as your incoming value has a TimeZone, you'll need to use ZonedDateTime to parse your input.
String createdDate = "2018-05-23T06:39:37+0000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
ZonedDateTime localDate = ZonedDateTime.parse(createdDate, formatter);
System.out.println(localDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")));
Output:
23/05/2018 06:39
The given input date String format
2018-05-23T06:39:37+0000
is incorrect so that you are getting ParseException since millisecond(SSS) part is missing from your date format yyyy-MM-dd'T'HH:mm:ss.SSSZ
So please try with
2018-05-23T06:39:37.235-0530
so below code should work
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
try {
Date parsedDate = simpleDateFormat.parse(createdDate);
createdDate = parsedDate.toString();
System.out.println(parsedDate.toString());
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
Ok, the first mistake (as you've pointed) is I didn't have milliseconds on the original String.
After removing "SSS" from the simpleDateFormat it works like a charm. So this is the final code:
String createdDate = comment.getCreatedDateTime();
SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
Date parsedDate = defaultDateFormat.parse(createdDate);
SimpleDateFormat finalDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
createdDate = finalDateFormat.format(parsedDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
mCommentDate.setText(createdDate);
Related
I got a timestamp as follows, 2019-10-17T07:10:39.021+10:30 but when I parse through the SimpleDateFormat then print again, it appear as 2019-10-17T07:40:39.021+11:00
Looks like it added the 30min to time then change the time zone. Is there is a way to fix that.
Date date = null;
String value = "2019-10-17T07:10:39.021+10:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault());
System.out.println("input :" + value);
try {
date = sdf.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("output :" + sdf.format(date));
Result
input :2019-10-17T07:10:39.021+10:30
output :2019-10-17T07:40:39.021+11:00
Should be same as input.
The date string you have 2019-10-17T07:10:39.021+10:30consists of offset, so from java-8 you can use OffsetDateTime
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime dateTime = OffsetDateTime.parse(date);
System.out.println(dateTime.toString()); //2019-10-17T07:10:39.021+10:30
Why are you using Locale.getDefault(), that parameter is not necessary. Can you try just calling it as below,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
I have these following Java.lang.String values that represents String value of TIMESTAMPTZ. I need to convert these Java.lang.String TO oracle.sql.TIMESTAMPTZ.
"2016-04-19 17:34:43.781 Asia/Calcutta",
"2016-04-30 20:05:02.002 8:00",
"2003-11-11 00:22:15.0 -7:00",
"2003-01-01 02:00:00.0 -7:00",
"2007-06-08 15:01:12.288 Asia/Bahrain",
"2016-03-08 17:17:35.301 Asia/Calcutta",
"1994-11-24 11:57:17.303"
I tried it by many ways.
Sample 1:
Tried it by using SimpleDateFormat
String[] timeZoneValues = new String[]{"2016-04-19 17:34:43.781 Asia/Calcutta", "2016-04-30 20:05:02.002 8:00", "2003-11-11 00:22:15.0 -7:00", "2003-01-01 02:00:00.0 -7:00", "2007-06-08 15:01:12.288 Asia/Bahrain", "2016-03-08 17:17:35.301 Asia/Calcutta", "1994-11-24 11:57:17.303"};
for(String timeZoneValue: timeZoneValues){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
try {
simpleDateFormat.parse(timeZoneValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
That thrown an Exception:
java.text.ParseException: Unparseable date: "2016-04-19 17:34:43.781 Asia/Calcutta"
at java.text.DateFormat.parse(DateFormat.java:357)
Sample 2:
Tried it by converting these String values directly into Timestamp or oracle.sql.TIMESTAMPTZ
String parse = "2016-04-19 17:34:43.781 8:00";
try {
Timestamp timestamp = Timestamp.valueOf("2016-04-19 17:34:43.781 8:00");
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.NumberFormatException: For input string: "781 8:000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.sql.Timestamp.valueOf(Timestamp.java:253)
Sample 3:
String parse = "2016-04-19 17:34:43.781 Asia/Calcutta";
DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis();
DateTime dateTime = dateTimeFormatter.parseDateTime(parse);
Timestamp timeStamp = new Timestamp(dateTime.getMillis());
Exception:
Invalid format: "2016-04-19 17:34:43.781 Asia/Calcutta" is malformed at " 17:34:43.781 Asia/Calcutta"
Sample 4:
try {
TIMESTAMPTZ timestamptz = new TIMESTAMPTZ(connection, (String) colValue);
}catch (Exception ex){
ex.printStackTrace();
}
Exception:
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
at java.sql.Timestamp.valueOf(Timestamp.java:249)
at oracle.sql.TIMESTAMPTZ.toBytes(TIMESTAMPTZ.java:1919)
at oracle.sql.TIMESTAMPTZ.<init>(TIMESTAMPTZ.java:253)
I am trying to insert the TIMESTAMPTZ value into Oracle database using Apache Metamodel and I have Java 1.7 installed on my system.
Your timestamps are not in a standard java parseable formats. So in order to parse them you need to write custom code for handling such formats.
Couple of observations:
Asia/Calcutta is not a valid Parseable TimeZone, hence you need some
mechanism to get corresponding timezone.
8:00 is also not a valid Parseable Timezone in java, hence you need
some mechanism to format it in a valid value +08:00
Keeping above points in mind, following code will do the needful for you.
SimpleDateFormat dateFormatTZGeneral = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
SimpleDateFormat dateFormatTZISO = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS XXX");
SimpleDateFormat dateFormatWithoutTZ = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String[][] zoneStrings = DateFormatSymbols.getInstance().getZoneStrings();
Date date = null;
String[] timeStampSplits = timestamp.split(" ");
if(timeStampSplits.length>2) {
String timezone = timeStampSplits[2];
//First Case Asia/Calcutta
if(Character.isAlphabetic(timezone.charAt(timezone.length()-1))) {
for(String[] zoneString: zoneStrings) {
if(zoneString[0].equalsIgnoreCase(timezone)) {
timeStampSplits[2] = zoneString[2];
break;
}
}
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZGeneral);
} else {
//Second Case 8:00
timeStampSplits[2] = formatTimeZone(timeStampSplits[2]);
timestamp = createString(timeStampSplits," ");
date = getDate(timestamp, dateFormatTZISO);
}
} else {
// Third Case without timezone
date = getDate(timestamp, dateFormatWithoutTZ);
}
System.out.println(date);
TIMESTAMPTZ oraTimeStamp = new TIMESTAMPTZ(<connection object>,new java.sql.Timestamp(date.getTime());
Above code uses following utility methods
private static Date getDate(String timestamp, SimpleDateFormat dateFormat) {
Date date = null;
try {
date = dateFormat.parse(timestamp);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
private static String createString(String[] contents, String separator) {
StringBuilder builder = new StringBuilder();
for (String content : contents) {
builder.append(content).append(separator);
}
builder.deleteCharAt(builder.length()-separator.length());
return builder.toString();
}
private static String formatTimeZone(String timeZone) {
String[] timeZoneSplits = timeZone.split(":");
DecimalFormat formatter = new DecimalFormat("+##;-#");
formatter.setMinimumIntegerDigits(2);
timeZoneSplits[0] = formatter.format(Integer.parseInt(timeZoneSplits[0]));
return createString(timeZoneSplits, ":");
}
This code is specifically written to cater your timestamp examples, any deviation might not be handled by this and it will need more customization.
Hope this helps you.
You have to parse the date according to the data coming i.e dynamic. For information about What constant used by android you have to follow the link
and in case of Java you have to follow link
Here is the code snippet of some different format
Sample 1
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzzz");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 Pacific Standard Time");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 2
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781 -08:00");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
Sample 3
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = null;
try {
date = sdf.parse("2016-04-19 17:34:43.781");
Log.e("date",""+date);
} catch (ParseException e) {
e.printStackTrace();
}
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
So as per these three set of sample you can parse any type of date time except the one format i.e "2016-04-19 17:34:43.781 Asia/Calcutta" as the time zone Asia/Calcutta or Asia/Bahrain can not get read by android or java. This is the format which gets supported by PHP as per my understanding. SO If you want to parse these type of format then I guess you have to write your custom SimpleDateFormat and have to identify these content and perform the calculation according to your need.
The Timestamp strings are in different format,
Ex-Here SimpleDateFormat uses pattern :
'yyyy-MM-dd HH:mm:ss.SSS XXX'
where X is to represent timezone in [ISO 8601 time zone][1] format.For this
timezone valid Timestamp Strings are (-08; -0800; -08:00).So,'Asia/Kolkata'
will not be parsed for Sample 1.
There are three type of Timezone pattern to be assigned to SimpleDateFormat.
**'Z'** - RFC 822 time zone.
**'z'** - General time zone.
**'X'** - ISO 8601 time zone.
So,either use different SimpleDateFormat's,or convert Timezone of all timestamp into same pattern of timezone and use a single SimpleDateFormat.
I am getting a date in the form of dd.mm.yyyy and want to save it as a proper object. It should be comparable to another date object. How do I realize this?
Use SimpleDateFormat as this:
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("12/05/2015");
Using JodaTime
String input = "03.01.2015";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
DateTime dt = DateTime.parse(input, formatter);
DateTime now = new DateTime();
System.out.println(dt.compareTo(now));
Use SimleDateFormat
String string = "03.01.2015";
DateFormat format = new SimpleDateFormat("MM.dd.yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date);
Try this code
try {
SimpleDateFormat sdf= new SimpleDateFormat("dd.MM.yyyy");
Date d = sdf.parse("19.05.2090");
System.out.println(d);
} catch (ParseException ex) {
ex.printStackTrace();
}
I accept the user input date in yyyy/mm/dd format. When I try to convert using SimpleDateFormat it shows "null";
my code for conversion is:
SimpleDateFormat dateofbirthFormat = new SimpleDateFormat("yyyy/mm/dd");
java.util.Date dateOfBirth = dateofbirthFormat.parse(birthdate);
why is it showing null?
MM not mm,
MM is for months,
mm is for minutes
SimpleDateFormat dateofbirthFormat = new SimpleDateFormat("yyyy/MM/dd");
try {
java.util.Date dateOfBirth = dateofbirthFormat.parse("1986/12/11");
System.out.println(dateOfBirth);
} catch (ParseException e) {
}
By yyyy/mm/dd I guest you mean years/Months/days. So you may try using
yyyy/MM/dd (note upcase use of MM).
SimpleDateFormat dateofbirthFormat = new SimpleDateFormat("yyyy/MM/dd");
java.util.Date dateOfBirth = dateofbirthFormat.parse(birthdate); .
I'm having a hard time Parsing/Formatting a Date string received back from a web service. I've attempted multiple approaches, but with no luck.
Sample Date String:
2011-10-05T03:00:00Z
Exception:
W/System.err(10072): java.text.ParseException: Unparseable date: "2011-10-05T05:00:00Z" (at offset 10)
W/System.err(10072): at java.text.DateFormat.parse(DateFormat.java:626)
Sample Code:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:SSSS");
Date date = formatter.parse(info.AiringTime);
I've found that if I remove the "T" between the date and the time and replace it with a space, it will format just fine. Anybody have any suggestions?
--UPDATE--
After looking deeper into the API documentation, I found this:
All response DateTime values are in UTC format. You need to apply the UTC offset to calculate the local time for display.
DateTime is a date-and-time value specified in one of the following formats:
UTC format: YYYY-MM-DDThh:mm:ssZ. For example: 2011-03-15T02:00:00Z.
Local time with an offset: YYYY-MM-DDThh:mm:ss + or - hh:mm (positive or negative offset). For example, for US Pacific time: 2011-03-14T06:00:00 -08:00.
Any suggestions on the UTC format approach?
You could try:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = dateString.replace("Z", "GMT+00:00");
Date date = dateFormat.parse(dateString);
The above code should correctly handle the case where a timezone is specified in the date. As Z represents the UTC/GMT timezone it is replaced by GMT so the SimpleDateFormat can interpret it correctly (i would love to know a cleaner way of handling this bit if anyone knows one).
Try,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
This pattern should parse the date you provide: "yyyy-MM-dd'T'HH:mm:ss'Z'".
If you want to use SimpleDateFormat and you have a limited number of variations, you can create separate formatters for each pattern and chain them:
Date date = formatter1.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter2.parse(info.AiringTime);
if (date == null)
{
date = formatter3.parse(info.AiringTime);
}
}
}
or put them in a list and iterate until non-null or no more formatters.
If you have too many patterns for this to be practical, you can parse it yourself or try one of these libraries.
This worked for me
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");
SimpleDateFormat viewFriendlyDateFormat = new SimpleDateFormat("dd/MMM/yyyy hh:mm:ss aaa");
String viewFriendlyDate = "";
try {
Date date = isoDateFormat.parse(timestamp);
viewFriendlyDate = viewFriendlyDateFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}