How to convert string to datetime in java using joda time - java

I am currently working on converting from date to string. After that I convert that string to datetime. But it error. Anyone can help me?
Here is the code.
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
SimpleDateFormat outFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String dt1 = outFormat.format(date1);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(dt1);

You're doing entirely too much work. Joda Time can convert for you in its parse(String, DateTimeFormatter) method.
DateTime dateTime = DateTime.parse(dt1, formatter);
Alternatively, if your string were in ISO8601 format (that is, yyyy-MM-dd'T'HH:mm:ssZ), you could just use parse(String) instead:
DateTime dateTime = DateTime.parse(dt1);

Related

Get formatted string from Calendar

I've got a Calendar Date in Java.
I need to convert it in a String with this format :
2020-12-29T00:00:00+01:00
How can I do it?
Thank you so much for your help.
Get the Date object by calling Calendar#getTime and format it using a SimpleDateFormat with the format, yyyy-MM-dd'T'HH:mm:ssXXX.
Note: Since the desired string has timezone offset of +01:00 hours, make sure you set the timezone of the SimpleDateFormat object to TimeZone.getTimeZone("GMT+1") before calling SimpleDateFormat#format.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date date = calendar.getTime();
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Another example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String dateTimeString = "2020-12-29T00:00:00+01:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date obj = sdf.parse(dateTimeString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(obj);
// Formatting this calendar object
Date date = calendar.getTime();
sdf.setTimeZone(TimeZone.getTimeZone("GMT+1"));
String formatted = sdf.format(date);
System.out.println(formatted);
}
}
Output:
2020-12-29T00:00:00+01:00
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Here’s a formatter for your desired format:
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX");
With this we may do:
ZoneId zone = ZoneId.of("Asia/Barnaul");
ZonedDateTime dateTime
= LocalDate.of(2020, Month.DECEMBER, 29).atStartOfDay(zone);
String formatted = dateTime.format(formatter);
System.out.println(formatted);
Output from this example snipoet is:
2020-12-29T00:00:00+07:00
If you cannot avoid getting a Calendar
If you are getting a Calendar object from a legacy API that you cannot afford to upgrade to java.time just now, convert it to ZonedDateTime. It is almost certainly really a GregorianCalendar (or formatting into that format would not make much sense), which makes the conversion straightforward.
Calendar yourCalendar = getCalendarFromLegacyApi();
ZonedDateTime dateTime
= ((GregorianCalendar) yourCalendar).toZonedDateTime();
The rest is as before, as is the output.
If you need to take into account the possibility that the Calendar is not a GregorianCalendar, use this slightly more complicated conversion instead:
ZonedDateTime dateTime = yourCalendar.toInstant()
.atZone(yourCalendar.getTimeZone().toZoneId());
Link
Oracle tutorial: Date Time explaining how to use java.time.

Parse function unable to parse string and throwing error in Java

Not able to parse the following date. Getting parse exception. Please help in finding error :
String myDate = "2020–03–01 3:15 pm";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm aa",Locale.ENGLISH);
Date date = sdf.parse(myDate);
The separator character that you have used to separate the year, the month and the day doesn't seem to be correct. I suggest you type the date-time string again instead of copying and pasting it from somewhere. I also recommend you switch from the outdated date-time API to the modern one.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String myDate = "2020-03-01 3:15 pm";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("u-M-d h:m a")
.toFormatter(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(myDate, formatter);
System.out.println(ldt);
}
}
Output:
2020-03-01T15:15
If you still want to use the legacy date-time API, you can do it as follows:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
String myDate = "2020-03-01 3:15 pm";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd h:mm aa", Locale.ENGLISH);
Date date = sdf.parse(myDate);
System.out.println(date);
}
}
Output:
Sun Mar 01 15:15:00 GMT 2020
Note that I've used a single h to match your date-time string.
From the looks of it your date string contains – (dash) instead of - (hyphen).
Try using hyphens in the date instead and see if it manages to parse it correctly.
Bonus ascii table details:
Dash (-):
.
Hyphen (-):

Parse String timestamp to Instant throws Unsupported field: InstantSeconds

I am trying to convert a String into an Instant. Can you help me out?
I get following exception:
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
at java.time.format.Parsed.getLong(Parsed.java:203)
at java.time.Instant.from(Instant.java:373)
My code looks basically like this
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
Instant result = Instant.from(temporalAccessor);
I am using Java 8 Update 72.
A simpler method is to add the default timezone to the formatter object when declaring it
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
Instant result = Instant.from(formatter.parse(timestamp));
Here is how to get an Instant with a default time zone. Your String can not be parsed straight to Instant because timezone is missing. So you can always get the default one
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
Instant result = Instant.from(zonedDateTime);
I wrote such simple function to perform the conversion:
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.time.ZonedDateTime;
import java.time.Instant;
import java.sql.Timestamp;
public class SqlTimestampParser {
public static Timestamp parseTimestamp(String dateTime, String format) throws Exception {
if (format == null || format.trim().length() == 0) {
throw new Exception("No format defined!");
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
ZonedDateTime timed = ZonedDateTime.parse(dateTime, formatter);
timed.format(formatter);
Instant x = Instant.from(timed);
return Timestamp.from(x);
}
}
With sample usage:
SqlTimestampParser.parseTimestamp('2020-09-17 16:20:35.294000+00:00',"yyyy-MM-dd HH:mm:ss.SSSSSSXXX")
First convert your date into util date using date format as you don't have time zone in your input. Then you can convert that date into Instant date. This will give you date with accurate time.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = "2016-02-16 11:00:02";
Date xmlDate = dateFormat.parse(timestamp);
dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Instant instantXmlDate = Instant.parse(dateFormat.format(xmlDate));

convert date from 2013-08-22T10:47:12+02:00 to 2013-08-22 10:47:12

Hy guys,
I would like to know how convert date with timezone like 2013-08-22T10:47:12+02:00 to another date 2013-08-22 10:47:12.
I try to do that with SimpleDateFormat object, but I have the same exception:
java.text.ParseException: Unparseable date: "2013-08-22T10:47:12+02:00"
Can you help me? thanks
UPDATE
I show here my failing code:
String CURRENT_TIME_PATTERN ="yyyy-MM-dd'T'HH:mm:yyX";
String NEW_TIME_PATTERN ="yyyy-MM-dd HH:mm:ss";
String data="2013-08-22T10:47:12+02:00";
SimpleDateFormat sdf = new SimpleDateFormat(CURRENT_TIME_PATTERN);
SimpleDateFormat output = new SimpleDateFormat(NEW_TIME_PATTERN);
Date d = sdf.parse(data);
String formattedTime = output.format(d);
System.out.println(formattedTime);
In this manner I will have exception over invalid parameter 'X'.
If I use this pattern String CURRENT_TIME_PATTERN ="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";, I'll get unparsable date exception.
I would suggest using Joda-Time to do any date and time formatting / parsing.
With the following imports:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
And the following code:
String input = "2013-08-22T10:47:12+02:00";
DateTimeFormatter formatterA = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTimeFormatter formatterB = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatterA.parseDateTime(input);
String output = dateTime.toString(formatterB);
You should try this if you always have T within your String :
String s = "2013-08-22T10:47:12+02:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:yyX"); // here X is for ISO 8601 time zone
Date parseDate = formatter.parse(s);
formatter.applyPattern("yyyy-MM-dd HH:mm:yy");
String formattedStr = formatter.format(parseDate);
System.out.println(formattedStr);
doc for ISO 8601 time zone
Update : removed String#replace() method and changed the formatter pattern to "yyyy-MM-dd'T'HH:mm:yyX".
Try this..
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String date = "2013-08-22T10:47:12+02:00";
Date date1 = dateFormat.parse(date);
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDate = dateFormat1.format(date1);
System.out.println("Date :: " + myDate);

Unparseable date exception when converting a string to "yyyy-MM-dd HH:mm:ss"

Hi I am trying to convert a string 19611015 to a date formate of ("yyyy-MM-dd HH:mm:ss") before storing it into a sybase database table. I have tried the below code which gives me the error:
Unparseable date: "19611015"
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.parse("19611015"));
I have been reading some long and complex solutions to this, some suggesting to use Locale. Could someone explain maybe an alternative simple solution to convert string I have to a date format I am after above. Thank you.
The date in string is in yyyyMMdd format and want to convert it into yyyy-MM-dd HH:mm:ss so use below code :
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = originalFormat.parse("19611015");
String formattedDate = targetFormat.format(date);
System.out.println(formattedDate);
Output :
1961-10-15 00:00:00
Achilles, below code might solve your problem:
package com.test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LongToDate {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(19611015 * 1000);
String dateFormatString = "yyyy-MM-dd HH:mm:ss";
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
String result = dateFormat.format(cal.getTime());
System.out.println(result);
//Output: 1969-12-10 15:46:18
}
}

Categories