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.
Related
Hello I have a method which adds a time to my current time.
What I am looking for is I want to add this code a local time info because doesnt get the local time in my country correctly.
I searched in the stackoverflow but couldnt find a similar topic for this case.
I am open your suggestions, thank you.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class MyClass {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 8);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
System.out.println(dateFormat.format(cal.getTime()));
}
}
I have changed the code with java.time utilities
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class MyClass {
public static void main(String args[]) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalDateTime date = LocalDateTime.now();
System.out.println(dateFormat.format(date));
System.out.println(dateFormat.format(date.plusHours(10)));
}
}
tl;dr
ZonedDateTime
.now( ZoneId.of( "Europe/Istanbul" ) )
.plusHours( 10 )
No, not Calendar
Never use the terrible Calendar & SimpleDateFormat legacy classes.
No, not LocalDateTime
Never call LocalDateTime.now. I cannot imagine a case where that is the right thing to do.
The LocalDateTime class lacks the context of a time zone or offset from UTC. So that class cannot represent a moment, a specific point on the timeline.
To track a moment, use: Instant, OffsetDateTime, or ZonedDateTime classes.
ZoneId
Specify your time zone.
ZoneId z = ZoneId.of( "Europe/Istanbul" ) ;
Or get the JVM‘s current default time zone.
ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime
Get the current moment.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Add time.
ZonedDateTime later = now.plusHours( 10 ) ;
Unfortunately you cannot really use the timezone because you get it from your operating system. If the OS gives you UTC, either configure it to Turkey or change it inside the application.
Since you know your location, just do this:
LocalDateTime date = LocalDateTime.now((ZoneId.of("Europe/Istanbul"));
This question from below might help :
how can i get Calendar.getInstance() based on Turkey timezone
You can also deduce your timezone using your internet provider. Below there are 2 examples.
timezone example 1
RestTemplate restTemplate = new RestTemplate();
String timezone = restTemplate.getForObject("https://ipapi.co/timezone", String.class);
timezone example 2
String timezone = restTemplate.getForObject("http://ip-api.com/line?fields=timezone", String.class);
After getting the timezone:
LocalDateTime date = LocalDateTime.now(ZoneId.of(timezone));
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.
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);
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.