This question already has answers here:
Convert LocalDate to LocalDateTime or java.sql.Timestamp
(7 answers)
Closed 4 years ago.
How do you convert a Localdatetime to timestamp? I want to use the new SE 8 date api because it is better than the util date and calendar. I plan to use localdatetime throughout my program and then place that date into a mysql database. I have looked for an answer but there doesn't seem to be very many questions and answers for java.time. This is a little of the code that I am testing. This is as far as I got.
LocalDateTime c = LocalDateTime.now();
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.getLong());
I think I need to convert it into a long first, but I don't know how. The api allows for converting individual elements like month and day, but not for the whole date. Since I'm already here, how do you convert back from timestamp? Should I just use jodatime?
I tried this:
LocalDateTime c = LocalDateTime.now();
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("this:" + c);
java.sql.Timestamp javaSqlDate = new java.sql.Timestamp(c.atZone(zoneId).toEpochSecond());
pst.setTimestamp(2, javaSqlDate);
This only saves the date around 1970. The system.print prints the current date correctly. I want it to save the current date.
LocalDateTime l = LocalDateTime.now();
Timestamp t = Timestamp.valueOf(l);
Source: https://coderanch.com/t/651936/databases/Convert-java-time-LocalDateTime-SE
First of all, you should decide if you really want to use LocalDateTime.
Below are some explanations about the difference, taken from here:
<...> LocalDateTime is not a point on the time line as Instant is, LocalDateTime is just a date and time as a person would write on a note. Consider the following example: two persons which were born at 11am, July the 2nd 2013. The first was born in the UK while the second in California. If we ask any of them for their birth date it will look that they were born on the same time (this is the LocalDateTime) but if we align the dates on the timeline (using Instant) we will find out that the one born in California is few hours younger than the one born in the UK (NB: to create the appropriate Instant we have to convert the time to UTC, this is where the difference lays).<...>
In order to get long from Instant you could use getEpochSecond() method.
In order to get long from LocalDateTime you should provide a timezone.
Related
This question already has answers here:
How to reduce one month from current date and stored in date variable using java?
(8 answers)
Closed 1 year ago.
I need to get the date today, and the date one month ago in the format yyyy-mm-dd
To get the date today i have:
val todaysDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date()).toString()
Which works as i want:
2021-05-12
However i cannot figure out how to get the date for one month ago in the same format.
I found this function in another thread but it returns "Mon Apr 12 18:24:37 GMT+02:00 2021"
fun getDaysAgo(daysAgo: Int): Date {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -daysAgo)
return calendar.time
}
How can i get the date one month ago in the same format? Thanks.
Edit:
The solution for me was actually very simple using the getDaysAgo function
var daysAgo= SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(getDaysAgo(30)).toString()
However Ole's answer below is probably better and the recommended way. Did not work for me as it requires api level 26 (android) and im on 23.
LocalDate from java.time
Keep and process dates as LocalDate objects, not as strings.
Only when you need to give string output, format your LocalDate into a string in the appropriate format.
Like many in the comments I recommend that you use java.time, the modern Java date and time API, for your date work. In Java code, still keeping processing and formatting separate and trusting you to translate to Kotlin yourself:
public static LocalDate get1MonthAgo() {
return LocalDate.now(ZoneId.systemDefault()).minusMonths(1);
}
public static String formatToIso8601(LocalDate date) {
return date.toString();
}
Assuming that you need to output the date 1 month ago as a string, use the two methods like this:
LocalDate oneMonthAgo = get1MonthAgo();
String oneMonthAgoFormatted = formatToIso8601(oneMonthAgo);
System.out.println(oneMonthAgoFormatted);
When I ran this evening in my time zone, the output was:
2021-04-12
I am exploiting the facts that the format you asked for is ISO 8601, the international format, and that LocalDate (and also the other date-time classes of java.time) produce(s) ISO 8601 format from their toString methods. So we need to specify no formatter. Which is good because fiddling with a format pattern string is always error-prone.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
This question already has answers here:
LocalDate to java.util.Date and vice versa simplest conversion? [duplicate]
(7 answers)
How do I get a Date without time in Java?
(23 answers)
Closed 3 years ago.
I want to get a Date without time, but always failed.
below is my codes:
long curLong = System.currentTimeMillis();
curLong = curLong - curLong % TimeUnit.DAYS.toMillis(1);
Date date = new Date(curLong);
System.out.println("date = " + date);
the output:
date = Mon Oct 28 08:00:00 CST 2019
anyone knows why? Thank you
It is not recommended to use java.util.Date anymore. It was called Date but doesn't necessarily hold only the date information but information about the time additionally.
Use this:
LocalDate today = LocalDate.now();
and print it as
System.out.println(today.format(DateTimeFormatter.ISO_DATE);
using the ISO date format. You can define your own formatting pattern using a
DateTimeFormatter.ofPattern("dd.MM.yyyy");
for example.
You can use java.time.LocalDate.now() to get just the date.
Anyway, your case doesn't work as you expect because you are doing nothing to remove the time from the date: you are just "repressing" it, that's why it's zero. If you want to continue this way you could always substring it (substring the Date.toString() of course I meant).
Hope I helped.
java.util.Date's javadoc states:
The class Date represents a specific instant in time, with millisecond precision.
Thats why you have date with time
If you want a date you can use : java.time.LocalDate.now() (Java 8+)
First of all, stop using the old java.util.Date. The new Java 8 date and time API has much better classes for all date and time operations.
The LocalDate class does exactly what you want.
The current date can be obtained by LocalDate.now().
It also has a lot of facilities to add and subtract days, months etc. and it takes into consideration all the calendar special cases for you.
How to calculate the difference between current day and date of the object that user had previously selected from jXDatePicker swing component and that had been added as Date to that object.
In my current code at the last line I'm getting this error message:
no suitable method found for between(Date, Date)
Date currentDate = new Date();
Date objDate = obj.getSelectedDate(); //getting date the user had
//previously selected and that been
//added to object
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);
You are mixing up the legacy Date-Time code with the new Java 8 Date-Time API. The ChronoUnit.between(Temporal, Temporal) method is from java.time.temporal package which takes two Temporal objects. It does not support the java.util.Date as an argument, hence the compilation error.
Instead of using the legacy Date class, you can use java.time.LocalDate class , and then get the difference between the two dates.
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
LocalDate objDate = obj.getSelectedDate(); // object should also store date as LocalDate
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);
Update
As per your comment , the objDate can only be a Date, so in this case you can use the inter-operability between the Legacy Date -Time and the Java 8 Date-Time classes.
LocalDateTime currentDate = LocalDateTime.now(ZoneId.systemDefault());
Instant objIns = obj.getSelectedDate().toInstant();
LocalDateTime objDtTm = LocalDateTime.ofInstant(objIns, ZoneId.systemDefault());
long daysDifference = ChronoUnit.DAYS.between(objDtTm, currentDate);
Update 2
As pointed out by Ole V.V in the comments, to handle Time Zone issues that may occur , calculating the difference using Instant is a better approach.
Instant now = Instant.now();
long daysDifference = obj.getSelectedDate()
.toInstant()
.until(now, ChronoUnit.DAYS);
I agree with Pallavi Sonal’s answer that when you can use the modern java.time classes, you should keep your use of the oldfashioned classes like Date to an absolute minimum. I don’t know JXDatePicker, but I see that its getDate method returns a Date. So the first thing you should do with this is convert it to a more modern thing.
It may seem from your question that in this case you are only concerned with days, not times. If this is correct, Pallavi Sonal is also correct that LocalDate is the correct class for you. I think that this conversion should work for you
LocalDate selectedDate = jXDatePicker.getDate()
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
This is with a bit of reservation for time zone issues since I don’t know in which time zone the date picker is giving you the date. Once you know that, you can fill in the correct time zone instead of ZoneId.systemDefault().
Unfortunately I am not aware of a date picker component that can give you a LocalDate directly. There could well be one, I hope there is, so it’s probably worth searching for one.
This question already has answers here:
Convert Joda LocalDate or java.util.Date to LocalDateTime having time at Start of the Day
(2 answers)
Closed 5 years ago.
I am trying to convert Joda LocalDate to Joda LocalDateTime, for that I am using the method toLocalDateTime(LocalTime.MIDNIGHT), as of now it is working
fine for example: for the given joda Localdate 2025-02-28 I getting the expected joda LocalDateTime 2025-02-28T00:00:00.000, But my fear is, whether this method works fine at all situation. For example during dayLight saving time zone anomalies..etc..
Update: I did a small research on this question, here it is
toLocalDateTime(LocalTime time) Documentation saying that: Converts LocalDate object to a LocalDateTime with LocalTime to fill in the missing fields.
As I initializing LocalTime with LocalTime.MIDNIGHT, from here LocalTime.MIDNIGHT is a static final field initialized to new LocalTime(0, 0, 0, 0);, you can see that it is a time values are hardcode to zero values with ISOChronology getInstanceUTC(), so I think I will get the required output without any issue.
From the documentation, we know that
LocalDate is an immutable datetime class representing a date without a time zone.
LocalDateTime is an unmodifiable datetime class representing a datetime without a time zone.
Internally, LocalDateTime uses a single millisecond-based value to represent the local datetime. This value is only used internally and is not exposed to applications.
Calculations on LocalDate are performed using a Chronology. This chronology will be set internally to be in the UTC time zone for all calculations.
We also know that the toLocalDateTime method of LocalDate class is implemented like this:
public LocalDateTime toLocalDateTime(LocalTime time) {
if (time == null) {
throw new IllegalArgumentException("The time must not be null");
}
if (getChronology() != time.getChronology()) {
throw new IllegalArgumentException("The chronology of the time does not match");
}
long localMillis = getLocalMillis() + time.getLocalMillis();
return new LocalDateTime(localMillis, getChronology());
}
Considering also that UTC has no Daylight saving time, we can conclude that you don't have to fear daylight saving problems nor time zone anomalies using the toLocalDateTime method because this method dont deal with timezones.
I have found some similar Que's on SO but had not find the solution.
I have today's Date as following: (Let's say this as Date1 and it's value as 2012-06-22)
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
Date start = cal.getTime();
String currentDate=dateformatter.format(start);
I'm retrieving 4 values from the user:
Particular Date (Assume 5)
Particular Month (Assume 1)
Particular Year (Assume 2012)
No. of days (Assume 7)
So this date, say Date2 becomes 2012-01-05 (yyyy-MM-dd) along with No. of days set to 7.
I want to compare Date 1 and Date 2-No. of days.
I know that by using following snippet, particular no. of days can be subtracted from a calender instance.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);
But since I'm having Date2 in form of String, I'm not able to follow this approach.
Any help appreciated.
Edit:
From your suggestions, I'll be able to convert String to Date by using parse method of SimpleDateFormat.
Now I've 2 Date Objects.
How do I find Difference between them in terms of days, months, and years?
How to Subtract particular no. of days, say 7, from a particular date, say 2012-01-05?
java.time
The question and the accepted answer have used the java.util Date-Time API and their parsing/formatting API, SimpleDateFormat which was appropriate thing to do using the standard library in 2012. In March 2014, Java 8 introduced the modern Date-Time API which supplanted the legacy API and since then it is highly recommended to use the modern Date-Time API.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Requirements copied from your question:
From your suggestions, I'll be able to convert String to Date by using
parse method of SimpleDateFormat.
Now I've 2 Date Objects.
How do I find Difference between them in terms of days, months, and
years?
How to Subtract particular no. of days, say 7, from a
particular date, say 2012-01-05?
Solution using java.time, the modern Date-Time API:
With java.time, you can parse your date string into a LocalDate and then find the Period between this date and the current date (which you obtain with LocalDate.now()). You can also subtract days, months, and years using methods like minusXxx/minus. You have similar methods (plusXxx/plus) for adding these units. Check the documentation of LocalDate to learn more about it.
Note: java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 2012-06-22).
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) {
LocalDate then = LocalDate.parse("2012-06-22");
LocalDate now = LocalDate.now();
Period period = Period.between(then, now);
System.out.println(period);
System.out.printf("%d years %d months %d days%n",
period.getYears(), period.getMonths(), period.getDays());
// Examples of subtracting date units
LocalDate sevenDaysAgo = now.minusDays(7);
System.out.println(sevenDaysAgo);
// Alternatively
sevenDaysAgo = now.minus(7, ChronoUnit.DAYS);
System.out.println(sevenDaysAgo);
}
}
Output from a sample run:
P10Y6M27D
10 years 6 months 27 days
2023-01-11
2023-01-11
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
use SimpleDateFormat to convert String (representing date) to Date
For example :
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-05");
If you can possibly use Joda Time instead of Date/Calendar, do so. It'll make your life easier.
If not, it sounds like you don't want to format the current date - instead, you want to parse Date2 from the user:
Date date2 = dateFormatter.parse(text);
Then you can either create a calendar and subtract a particular number of days, or (if you're talking about elapsed time - you need to think about your behaviour around DST transitions and time zones here) you could just subtract 7 * 24 * 60 * 60 * 1000 milliseconds from date2.getTime().
Fundamentally, you should convert out of a string format as earlier as possible, and only convert to a string format when you really need to - certainly not for comparisons. The natural representation of this data is as a Date or Calendar (assuming you're sticking with the JDK), so work towards getting your data into that representation.
You have several genuine "business" questions to think about though:
Do you want to compare the current date with the date the user's given, or the current date and time with the date the user's given?
What time zone do you want to use for the user's input?
Are you thinking about elapsed days or "logical" days? Because 7 * 24 hours earlier than 1.30am may be 2.30am or vice versa, due to DST transitions
You should answer all those questions before you try to implement your code, as it will affect the representation you use. Also, write unit tests for everything you can think of before you start the implementation.
From my understanding you have two dates now and you want to subtract a particular number of days from date.
First you can use SimpleDateFormat to convert a date to string and string to date
Now to subtract days say 7. you can get time of the date and subtract 7*24*60*60*1000 from it
long daybeforeLong = 7 * 24 * 60 * 60 * 1000;
try {
Date todayDate = new Date();
long nowLong = todayDate.getTime();
Date beforeDate = new Date((nowLong - daybeforeLong));
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can make use of Comparator provided by java will do work of comparing and sorting the dates too.
here is the link
hope you get what you was looking for..