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.
Related
I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
} catch (ParseException e) {
e.printStackTrace();
}
For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?
Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
// get / provide the String to be parsed
String expDate = "31.12.2032";
// provide a pattern that parses such a date
String pattern = "dd.MM.uuuu";
// create a DateTimeFormatter with this pattern
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
// parse the String with the DateTimeFormatter
LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
// print the default format of a LocalDate
System.out.println(expLocalDate);
// print the LocalDate using the pattern created for parsing
System.out.println(expLocalDate.format(dtf));
// create a totally different DateTimeFormatter inline and format the date differently
System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
Locale.ENGLISH)));
}
The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032
Try this way
String expDate = mDatePickerBtn.getText().toString();
Date date = null;
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
try {
date = format.parse(expDate);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
format1.format(date);
expDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
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'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);
In mysql, i have a field time_entered of type datetime (sample data: 2012-06-20 16:00:47). I also have a method, getTimeEntered(), that returns the value as String. I want to display the date in this format 2012-06-20 using DateTimeFormat from GWT.
here's my code:
String date = aprHeaderDW.getTimeEntered();
DateTimeFormat fmt = DateTimeFormat.getFormat("MM-dd-yyyy");
dateEntered.setText("" + fmt.format(date));
The problem is, the format method doesn't accept arguments as String. So if there's only a way I could convert the date from String to Date type, it could probably work. I tried typecasting but didn't work.
You should be able to just use DateTimeFormat.
Date date = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
String dateString = DateTimeFormat.getFormat("yyyy-MM-dd").format(date);
Otherwise there is a light-weight version of SimpleDateFormat that supports this pattern.
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
Hi There are two options.
The first is as it is already a string you could use a regular expression to modify the format.
The second is using a SimpleDateFormater you can parse the string to a date then back again.
For example:
public class DateMerge {
public static void main(String arg[])
{
String out = dateConvert("2012-06-20 16:00:47");
System.out.println(out);
}
public static String dateConvert (String inDate)
{
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = (Date)formatter.parse(inDate);
formatter = new SimpleDateFormat("dd-MM-yyyy");
String outDate = formatter.format(date);
return outDate;
} catch (ParseException e)
{System.out.println("Exception :"+e); }
return null;
}
}
You may use like this.
String date = "2012-06-20 16:00:47";
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
String lDate=sf.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date));
System.out.println(lDate);
Output:
2012-06-20
After trying a lot of times I came up with a solution, based on #Keppil and adding my own code.
Here's Keppil's suggested solution for converting String datetime into Date type:
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-06-20 16:00:47");
...but my second requirement is to display just the date like 2012-06-20. Even though I removed HH:mm:ss, it still displayed the time like this 2012-06-20 00:00:00.
Here's my final solution:
Date date = null;
String d = rs.getString(SQL_CREATION_TIME); // assigns datetime value from mysql
// parse String datetime to Date
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(d);
System.out.println("time entered: "+ date);
} catch (ParseException e) { e.printStackTrace(); }
// format the Date object then assigns to String
Format formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
String s = formatter.format(date);
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();
}