Create LocalDate Object from Integers - java

If I already have a date's month, day, and year as integers, what's the best way to use them to create a LocalDate object? I found this post String to LocalDate , but it starts with a String representation of the date.

Use LocalDate#of(int, int, int) method that takes year, month and dayOfMonth.

You can create LocalDate like this, using ints
LocalDate inputDate = LocalDate.of(year,month,dayOfMonth);
and to create LocalDate from String you can use
String date = "04/04/2004";
inputDate = LocalDate.parse(date,
DateTimeFormat.forPattern("dd/MM/yyyy"));
You can use other formats too but you have to change String in forPattern(...)

In addition to Rohit's answer you can use this code to get Localdate from String
String str = "2015-03-15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(str, formatter);
System.out.println(dateTime);

Related

Format date from String to LocalDate

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());

Convert the Specific string to date and check it is greater than current date

I have a string s="2020-04-07T13:43:49-05:00"
i have to check if its greater than current date and i tried using instant date
Instant timestamp = Instant.parse(string);
But did not work and i tried with LocalDate
LocalDate date = LocalDate.parse(string, format);
this is also not working, how to parse it and check
You should parse it into OffsetDateTime since date string has an offset
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
String s="2020-04-07T13:43:49-05:00";
OffsetDateTime dateTime = OffsetDateTime.parse(s);
and then check weather it is greater than or not using isBefore or isAfter by converting into LocalDateTime
LocalDateTime.now().isBefore(dateTime.toLocalDateTime())
You can also compare OffsetDateTime directly using isBefore and isAfter
OffsetDateTime.now().isBefore(dateTime)
This works fine for me using Java (jshell) 13:
jshell> import java.time.Instant
jshell> Instant.parse("2020-04-07T13:43:49-05:00")
$2 ==> 2020-04-07T18:43:49Z
Use SimpleDateFormat for this. Take your string and format it to the date and then check for it.
Date date= new Date();
String targetDate="2020-04-07 13:43:49";
Date date2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(targetDate);
Now you can just check the two date by
if(date.getTime()>date2.getTime())
If you want to do it opposite way you can do that too.
Date date= new Date();
String currentDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)
now just check the two strings with if condition.

how to print DateTime value

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.

"plusDays" doesn't advance LocalDate in Java 8

Why is LocalDate not changing even though there is no error during running?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse("2005-12-12", formatter);
date.plusDays(3);
System.out.println(date.toString());
Output:
2005-12-12
Anything I missed out?
LocalDate is immutable
date = date.plusDays(3);
As a String, it doesn't have an effect calling a method on it without assigning the result :
date = date.plusDays(3);
Read More

How to Convert String to LocalDateTime?

I have a string "2015-09-17T12:00". How can I convert this String to LocalDateTime in format "yyyy-MM-dd HH:mm" and then convert it back to String?
you can Replace T with whitespace(s):
String str="2015-09-17T12:00";
str.replace("T"," ");
afterwards convert to Date using SimpleDateFormat;
We can go with DateTimeFormatter, its thread safety.
Refer to below url:
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
sample program on converting String to Local Date Time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 'T' HH:mm");
LocalDateTime localDateTime = LocalDateTime.parse("2019-18-04 T 18:51", formatter);
Local Date time provides lot of method to get the hours or minutes or seconds
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

Categories

Resources