Folks!
Could any one help me find the way out this situation?
I'm aware that java.util.Date is deprecated, but my work is all based on it.
I'm having trouble to return the age in Years from the User.
I have these two dates:
Date nascimento = dashboard.getDtNascimento();
Date creationTime = new Date(session.getCreationTime());
That first Date come from a ArrayList that contains the user BirthDay.
The second one come from the user session..
How can I return the age having those two Dates? How can I do the math?
Is that any kind of way to parse those Dates into LocalDate perhaps...
Thank you guys!
You can get an Instant from java.util.Date. From the Instant, you can get an OffsetDateTime and from that, you can get a LocalDate. Finally, you can use Period.between to get Period between the LocalDates and from the Period, you can get years.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = sdf.parse("1975-08-27");
Date endDate = sdf.parse("2020-02-15");
OffsetDateTime startOdt = startDate.toInstant().atOffset(ZoneOffset.UTC);
OffsetDateTime endOdt = endDate.toInstant().atOffset(ZoneOffset.UTC);
int years = Period.between(startOdt.toLocalDate(), endOdt.toLocalDate()).getYears();
System.out.println(years);
}
}
Output:
44
Yes, you can convert these to LocalDate like this...
Date creationTime = new Date(session.getCreationTime());
LocalDate localCreationTime = creationTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
If I understand your question you want to find the difference between these dates?
If you convert to LocalDate you can do this:
long age = YEARS.between(localNascimento, localCreationTime);
Related
I'm trying to take two strings and make it into a Date object. I'm having trouble trying to work out what formats I need to use.
The first string is a date and is in the format of : 5th Jan
The second string is a time and is in the format of : 8:15
The main issue is what the format would be for the 5th
Since your date string, 5th Jan doesn't have a year, you will have to use some default year e.g. the current year, which you can get from LocalDate.now(). You can put defaults using DateTimeFormatterBuilder#parseDefaulting. Additionally, you can also make the parser
case-insensitive by using DateTimeFormatterBuilder#parseCaseInsensitive.
In order to parse a date string, 5th Jan, you can use the pattern, d'th' MMM. However, in order to deal with other suffixes like in 3rd, 1st etc., you should use the pattern, d['th']['st']['rd']['nd'] MMM where the patterns inside the square bracket are optional.
In order to parse a time string like 8:15, you can use the pattern, H:m.
Demo:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
DateTimeFormatter dtfForDate = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseDefaulting(ChronoField.YEAR, date.getYear())
.appendPattern("d['th']['st']['rd']['nd'] MMM")
.toFormatter(Locale.ENGLISH);
DateTimeFormatter dtfForTime = DateTimeFormatter.ofPattern("H:m", Locale.ENGLISH);
String strDate = "5th Jan";
String strTime = "8:15";
LocalDateTime ldt = LocalDate.parse(strDate, dtfForDate)
.atTime(LocalTime.parse(strTime, dtfForTime));
// Print the default string value i.e. the value returned by ldt.toString()
System.out.println(ldt);
// The default format omits seconds and fraction of second if they are 0. In
// order to retain them in the output string, you can use DateTimeFormatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss");
String formatted = dtf.format(ldt);
System.out.println(formatted);
}
}
Output:
2021-01-05T08:15
2021-01-05T08:15:00
Learn about the modern date-time API from Trail: Date Time.
So am parsing json and sometimes the string I receive which contains the date comes full(dd-mm-yyyy) , and sometimes I only receive yyyy which I dont seem to able to convert to date ,so if anyone can help
As per your business requirement, you can default the month and the day-of-month to the required value using DateTimeFormatterBuilder#parseDefaulting e.g. in the following code, I have defaulted the month and the day-of-month to that of today:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;
class Main {
public static void main(String[] args) {
// Test
System.out.println(parseToDate("10-10-2020"));
System.out.println(parseToDate("2020"));
}
static LocalDate parseToDate(String str) {
LocalDate today = LocalDate.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[dd-MM-uuuu][uuuu]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue())
.parseDefaulting(ChronoField.DAY_OF_MONTH, today.getDayOfMonth())
.toFormatter(Locale.ENGLISH);
return LocalDate.parse(str, formatter);
}
}
Output:
2020-10-10
2020-12-12
Note: The pattern, [dd-MM-uuuu][uuuu] has two optional patterns, dd-MM-uuuu and uuuu.
How am I able to get hijradate from the code below but instead of now() I would like to get this from a future date.
java.time.chrono.HijrahDate hijradate = java.time.chrono.HijrahDate.now();
System.out.println("hijradate "+hijradate);
It’s straightforward when you know how:
LocalDate gregorianDate = LocalDate.of(2019, Month.FEBRUARY, 22);
HijrahDate hijradate = HijrahDate.from(gregorianDate);
System.out.println(hijradate);
This printed
Hijrah-umalqura AH 1440-06-17
If by Gregorian date you meant that you had your date in a GregorianCalendar object (typically from a legacy API that you cannot change or don’t want to change just now):
GregorianCalendar gregCal = // ...
ZonedDateTime gregorianDateTime = gregCal.toZonedDateTime();
System.out.println(gregorianDateTime);
HijrahDate hijradate = HijrahDate.from(gregorianDateTime);
System.out.println(hijradate);
Output in one run on my computer was:
2019-02-22T00:00+03:00[Asia/Riyadh]
Hijrah-umalqura AH 1440-06-17
EDIT: For the sake of completeness here are my imports so you know exactly which classes I am using:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.chrono.HijrahDate;
import java.util.GregorianCalendar;
EDIT: To get the month: use your search engine. I used mine and found:
int month = hijradate.get(ChronoField.MONTH_OF_YEAR);
System.out.println(month);
String formattedMonthName
= hijradate.format(DateTimeFormatter.ofPattern("MMMM", new Locale("ar")));
System.out.println(formattedMonthName);
This prints
6
جمادى الآخرة
The last lines are inspired from this answer.
this is my first time asking, I couldn't find explanation in all internet, so here you go:
I'm writing a simple function to calculate the date that was x days ago, so I wrote this code that was working very ok, until today, the calculated past date was 1 year in the future, but not for all the values, only 11 days ago, the rest was ok.
If you execute this code today you'll have this output: you can execute it here
difference:-11
2015-12-28
difference:-12
2014-12-27
As you can see, I though it was an issue parsing from Calendar to Date, also I've check that in Calendar the values were totally ok, but the moment I transfer to Date it doesn't work, I tried to do this cast manually but the functions are deprecated.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(getDate(-11, "YYYY-MM-dd"));
System.out.println(getDate(-12, "YYYY-MM-dd"));
}
public static String getDate(int offset, String SimpleFormat) {
DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, offset);
Date todate1 = cal.getTime();
long diff = todate1.getTime()-(new Date()).getTime();
System.out.println("difference:"+diff/ (24 * 60 * 60 * 1000));
String fromdate = dateFormat.format(todate1);
return fromdate;
}
}
Later I found a nice library called Joda-Time very nice and fast, so I changed the code to work with it, but surprise the same issue.
DateFormat dateFormat = new SimpleDateFormat(SimpleFormat);
DateTime today = new DateTime();
String fromdate = dateFormat.format(today.plus(Period.days(offset)).toDate());
So far I've also check that adding 350 days or so, into this 11 days period it gives a wrong date too.
I know I can use Joda-time formatter, but still I can't find exactly what's the problem, any help would be nice :)
(for the ones who ever had this issue):
DateTimeFormatter fmt = DateTimeFormat.forPattern(SimpleFormat);
The problem isn't with the Date or DateTime, but rather with the formatter.
YYYY means the ISO Week Year. However, the ISO Week year for the last partial week of the year is the next year.
yyyy means the calendar year, which is what you really wanted.
I want to convert java.time.LocalDate into java.util.Date type. Because I want to set the date into JDateChooser. Or is there any date chooser that supports java.time dates?
Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
That assumes your date chooser uses the system default timezone to transform dates into strings.
Here's a utility class I use to convert the newer java.time classes to java.util.Date objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
Edited based on #Oliv comment.
Disclaimer: For illustrating existing java apis only. Should not be used in production code.
You can use java.sql.Date.valueOf() method as:
Date date = java.sql.Date.valueOf(localDate);
No need to add time and time zone info here because they are taken implicitly.
See LocalDate to java.util.Date and vice versa simplest conversion?
java.time has the Temporal interface which you can use to create Instant objects from most of the the time classes. Instant represents milliseconds on the timeline in the Epoch - the base reference for all other dates and times.
We need to convert the Date into a ZonedDateTime, with a Time and a Zone, to do the conversion:
LocalDate ldate = ...;
Instant instant = Instant.from(ldate.atStartOfDay(ZoneId.of("GMT")));
Date date = Date.from(instant);
This works for me:
java.util.Date d = new SimpleDateFormat("yyyy-MM-dd").parse(localDate.toString());
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#toString--
In order to create a java.util.Date from a java.time.LocalDate, you have to
add a time to the LocalDate
interpret the date and time within a time zone
get the number of seconds / milliseconds since epoch
create a java.util.Date
The code might look as follows:
LocalDate localDate = LocalDate.now();
Date date = new Date(localDate.atStartOfDay(ZoneId.of("America/New_York")).toEpochSecond() * 1000);
Kotlin Solution:
1) Paste this extension function somewhere.
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
2) Use it, and never google this again.
val myDate = myLocalDate.toDate()
public static Date convertToTimeZone(Date date, String tzFrom, String tzTo) {
return Date.from(LocalDateTime.ofInstant(date.toInstant(), ZoneId.of(tzTo)).atZone(ZoneId.of(tzFrom)).toInstant());
}
LocalDate date = LocalDate.now();
DateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
try {
Date utilDate= formatter.parse(date.toString());
} catch (ParseException e) {
// handle exception
}
localDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
Try this:
public Date convertFrom(LocalDate date) {
return Date.valueOf(date);
}
Simple
public Date convertFrom(LocalDate date) {
return java.sql.Timestamp.valueOf(date.atStartOfDay());
}
java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());