I'm using JodaTime to get the date and time of creation of an account. The format being
2017-04-05T12:38:35.585
When I get this I store it in my database as a string so I've looked around for ways to format this from a string to LocalDate but haven't been succesful in anything I've found online. My next step is a horrible solution in my opinion to loop through the string until I find the T and remove everything after it. So I'm left with
2017-04-05.
But Ideally if possible have the date as
05/04/2017
Use the ISODateTimeFormat to get a LocalDateTime and from this get the LocalDate.
Be careful to use the right Locale
String input="2017-04-05T12:38:35.585";
LocalDateTime ldt = ISODateTimeFormat.localDateOptionalTimeParser()
.withLocale(Locale.ENGLISH)
.parseLocalDateTime(input);
System.out.println(ldt.toLocalDate());//prints 2017-04-05
I'm using joda-time 2.7.
LocalDateTime class has a constructor that takes a String and parses it. Then you just call toString() method with the pattern you want:
String input = "2017-04-05T12:38:35.585";
LocalDateTime d = new LocalDateTime(input);
System.out.println(d.toString("dd/MM/yyyy"));
Output:
05/04/2017
Note: you can also use ISODateTimeFormat to parse and a DateTimeFormatter instead of toString() to get the output:
LocalDateTime d = ISODateTimeFormat.localDateOptionalTimeParser().parseLocalDateTime(input);
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
System.out.println(fmt.print(d));
The output will be the same.
Related
I have a problem parsing a String to LocalDate.
According to similar questions on Stackoverflow and documentation I am using the correct values dd (day of the month), MM (month of the year) and yyyy (year).
My String
String mydate = "18.10.2022 07:50:18";
My parsing test code
System.out.println(
LocalDate.parse(testPasswordExp)
.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")
)
);
Error:
Caused by: java.lang.RuntimeException:
java.time.format.DateTimeParseException:
Text '18.10.2022 07:50:18' could not be parsed at index 0
The main problem of your code example is that you first parse the String to a LocalDate without the use of a suitable DateTimeFormatter and then format() it with a DateTimeFormatter that tries to format hour of day, minute of hour and second of minute which just aren't there in a LocalDate.
You can parse this String to a LocalDate directly, but better parse it to a LocalDateTime because your String contains more than just information about
day of month
month of year
year
Your myDate (and probably the testPasswordExp, too) has a time of day. You can get a LocalDate as the final result that way, too, because a LocalDateTime can be narrowed down toLocalDate().
A possible way:
public static void main(String[] args) {
// example datetime
String testPasswordExp = "18.10.2022 07:50:18";
System.out.println(
LocalDateTime // use a LocalDateTime and…
.parse( // … parse …
testPasswordExp, // … the datetime using a specific formatter,
DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss")
).toLocalDate() // then extract the LocalDate
);
}
Output:
2022-10-18
You don't use the specified format for parsing, you use it to format the parsed date.
LocalDate.parse(mydate)
… uses the default ISO_LOCAL_DATE format. You are looking for this overload:
LocalDate.parse(mydate, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"))
This method uses the specified format for parsing string to date. See this code run at Ideone.com.
Note that you are using LocalDate, meaning it will throw away the time part, keeping only the date after parsing. You probably meant to use LocalDateTime.
You can use
String mydate = "18.10.2022 07:50:18";
LocalDate ld = LocalDate.parse(mydate, DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
System.out.println(ld.toString());
I'm getting this date from bing search and have difficulty to parse it to date, I need
the time as well.
""2021-09-02T13:16:00.0000000Z""
I'm doing this:
public static Date parseDate(String publishedDate) {
String dateStr = publishedDate.replaceFirst("T", "");
SimpleDateFormat formatter = null;
if (publishedDate.length() > 10) {
formatter = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
} else {
formatter = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = null;
try {
date = formatter.parse(publishedDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
getting the following error:
java.text.ParseException: Unparseable date: ""2021-09-02T13:16:00.0000000Z""
at java.base/java.text.DateFormat.parse(DateFormat.java:396)
Parse the quotes too; use java.time.Instant
Like many others I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Your string contains double quotes first and last. You can deal with them in two ways:
If there’s a way that you can get your string from Bing search without the quotes, do that. Then Instant.parse() will parse your string, and you’re done.
Otherwise java.time can parse the quotes too.
For parsing the quotes use the following formatter:
private static final DateTimeFormatter BING_INSTANT_PARSER
= new DateTimeFormatterBuilder().appendLiteral('"')
.append(DateTimeFormatter.ISO_INSTANT)
.appendLiteral('"')
.toFormatter();
Then parse like this:
String stringFromBing = "\"2021-09-02T13:16:00.0000000Z\"";
Instant instant = BING_INSTANT_PARSER.parse(stringFromBing, Instant::from);
System.out.println("String to parse: " + stringFromBing);
System.out.println("Result: " + instant);
Output:
String to parse: "2021-09-02T13:16:00.0000000Z"
Result: 2021-09-02T13:16:00Z
Which java.time class to use?
Assuming that your string always comes with the Z at the end, denoting UTC, Instant is the correct class to use. OffsetDateTime and ZonedDateTime will work too, but I consider them overkill. You don’t want to use LocalDateTime since you would then throw away the essential information that the string is in UTC.
Link
Oracle tutorial: Date Time explaining how to use java.time.
What you are dealing with is called Time Stamp,
there are Duration and INSTANT classes to deal with it.
This page explain it all
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
As #Basil Bourque suggested, we dont need DateTimeFormatter because Instant.parse() by default uses UTC. Also, we can use OffsetDateTime instead of ZonedDateTime (more detailed),
String date = "2021-09-02T13:16:00.0000000Z";
Instant timeStamp = Instant.parse(date);
// To get Time or Date," with Instant you must provide time-zone too"
ZonedDateTime dateTimeZone = ZonedDateTime.ofInstant(timeStamp, ZoneOffset.UTC);
System.out.println(dateTimeZone);
System.out.println(dateTimeZone.toLocalDate());// can also be tolocalTime
I'm querying database and getting date in this format "01-SEP-22"
I want to convert this date into this format "yyyy-MM-dd" in Java. Is there any way I can do this.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work.
In order to parse the month abbreviation in all upper case (like SEP) we need to instruct it to apply case insensitive parsing.
We can use DateTimeFormatterBuilder to build a DateTimeFormatter with such an instruction.
private static final DateTimeFormatter oracleFormatter
= new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uu")
.toFormatter(Locale.ROOT);
The rest goes smoothly:
String stringFromOracle = "01-SEP-22";
LocalDate date = LocalDate.parse(stringFromOracle, oracleFormatter);
String formattedString = date.toString();
System.out.println(formattedString);
Output is:
2022-09-01
For generating the string I am exploiting the fact that LocalDate.toString() gives the format that you asked for, so I am not using any formatter explicitly. The format is known as ISO 8601 and as this name says, is an international standard.
Suggestions for improvement
Don’t retrieve your date as a String from Oracle. Retrieve a LocalDate directly and save the parsing.
Don’t convert a date from one string format to another. In your program keep the date as a LocalDate. If you need to take string input (which is not the case here), parse the string into a LocalDate immediately. Only when you need to give string output (to the user or in data exchange with another system, for example), format the LocalDate into a string in the required format.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
You can simply use DateTimeFormatter:
public String convertDate(String dateStr) throws ParseException {
String[] split = dateStr.split("-");
split[1] = split[1].substring(0, 1).toUpperCase() + split[1].substring(1).toLowerCase();
dateStr = String.join("-", split);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateStr, dateFormatter);
return date.toString();
}
#Test
public void test_convertDate() throws ParseException {
assertEquals("2022-09-01", convertDate("01-SEP-22"));
}
I have this code and I want to print out the time as String without the 'T' character between date and time.
String datetime4 =new StringBuilder().append(date4).append(time4).toString();
DateTime newdt=new DateTime(datetime4);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
newdt = formatter.parseDateTime(datetime4);
System.out.println(newdt);
Notice that date4 and time4 are String variables.
It will print:
2017-11-04T11:23:00.000+02:00
One way of doing it:
String date4 = "2017-02-02";
String time4 = "12:00:00";
//To parse it to Temporal object
DateTime dateTime = DateTime.parse(date4 +"T"+ time4);
// to output it as String in a prefered format (Thanks #Hugo)
System.out.println(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
If you prefer Java 8 you will need to use formatter I think, LocalDateTime doesn't overload toString in the same way as JodaTime.
But not sure why you want to do this? seems like just appending both date and time is enough? Anyway if you want to parse to the date you need to put T as is needed to pass it as a valid date time format to DateTime as well as LocalDateTime if using Java8, then you can reformat it as you wish.
String date4 = "2017-02-02";
String time4 = "12:00:00";
LocalDateTime dateTime = LocalDateTime.parse(date4 +"T"+ time4);
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
Using Java 8 LocalDateTime;
LocalDateTime dateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
DateTimeFormatter desiredFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
dateTime = LocalDateTime.parse("2017-06-01T12:10:10", formatter);
System.out.println(desiredFormat.format(dateTime));
When you do:
System.out.println(newdt);
You're printing the newdt variable, and internally println calls the toString() method on the object.
As this variable's type is DateTime, this code outputs the result of newdt.toString(). And Datetime.toString() method uses a default format that contains the "T".
If you want the output String to have a different format, you can do something like this:
System.out.println(newdt.toString("yyyy-MM-dd HH:mm:ss"));
The output will be:
2017-11-04 11:23:00
(without the "T")
You can use this version of toString with any pattern accepted by DateTimeFormatter.
You can also create another DateTimeFormatter for the format you want:
DateTimeFormatter withoutT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(withoutT.print(newdt));
The output will be the same, it's up to you to choose.
I want to parse a date string like 2011-11-30 like this:
LocalDateTime.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE)
But I get the following exception:
java.time.format.DateTimeParseException: Text '2011-11-30' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor
If I pass a date and time string everything works as expected:
LocalDateTime.parse("2011-11-30T23:59:59", DateTimeFormatter.ISO_LOCAL_DATE_TIME)
How can I parse a date like 2011-11-30 to a LocalDateTime (with a default time)?
As #JB Nizet suggested, the following works
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = localDate.atTime(23, 59, 59);
System.out.println(localDateTime); // 2011-11-30T23:59:59
How can I parse a date like 2011-11-30 to a LocalDateTime (with a default time)?
Parse it first in a LocalDate
Use LocalDateTime atTime() method to set your default time
Note: Use of DateTimeFormatter.ISO_LOCAL_DATE is superfluous for parse(), see API LocalDate#parse()
The sample below use some magic numbers, wich should be avoid (What is a magic number, and why is it bad?).
Instead of using the method atTime(hour, minute, second),
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = localDate.atTime(23, 59, 59);
you can use the LocalTime constants, such as LocalTime.MAX, (23:59:59), LocalTime.MIN (00:00:00), LocalTime.MIDNIGHT (23:59:59) or LocalTime.NOON (12:00:00)
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
It is better for maintainability and cross-reference.
Why I've written this answer despite existing answers
Unfortunately, all of the existing answers are only partially correct. They lack the following important aspects of the modern date-time API:
Using ISO format while parsing a date string
How to apply the current time to an instance of LocalDateTime to get a new instance of LocalDateTime with the current time
Question posted by OP:
How can I parse a date like 2011-11-30 to a LocalDateTime (with a
default time)?
Answer
There are two problems with your approach:
Since you are parsing a date string, you should have used LocalDate#parse instead of LocalDateTime#parse.
Since your date string is already in the ISO pattern, you need not specify this pattern using DateTimeFormatter explicitly as LocalDate.parse uses this pattern by default.
Apart from these two problems, you will need to use LocalDateTime#with to apply the current time to an instance of LocalDateTime to get a new instance of LocalDateTime with the current time.
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
// No need to specify DateTimeFormatter as the string is already in ISO format
LocalDate date = LocalDate.parse("2011-11-30");
System.out.println(date);
// Get LocalDateTime from LocalDate
LocalDateTime ldt = date
.atStartOfDay() //Convert to LocalDateTime with 00:00
.with(LocalTime.now()); //Adjust to current time
System.out.println(ldt);
}
}
Output:
2011-11-30
2011-11-30T11:53:39.103150
Note: Learn more about the modern date-time API from Trail: Date Time.