From php to Java - mktime and date - java

I am trying to change a php script to java but I'm stuck in these two lines of code. Does anyone know what the equivalent code is?
$Menarche = mktime(2, 0, 0, $Month, $Dday, $Year);
$DueDate = $Menarche + 86400*(280 + ($MCL - 28));

You just need to create a LocalDateTime from the data. This is a representation of a particular date and time, but without a timezone.
final int month = 11;
final int day = 5;
final int year = 1605;
final LocalDateTime localDateTime = LocalDateTime.of(year, month, day, 2, 0, 0);
Now to print it, we can use a DateTimeFormatter:
final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
System.out.printf("A date to remember: %s%n", localDateTime.format(formatter));
Output:
A date to remember: 1605-11-05T02:00:00
To do arithmetic with a LocalDateTime we can simply use of the of many plusXXX methods, for example using months:
final LocalDateTime dueDate = localDateTime.plusMonths(9);
System.out.printf("Nine months later: %s%n", dueDate.format(formatter));
Output:
A date to remember: 1606-08-05T02:00:00
Or, if we have a precise duration - we cannot use months because they are "estimated" - you can create a Duration:
final Duration gestation = Duration.ofDays(280);
final LocalDateTime dueDate = localDateTime.plus(gestation);

Related

How to get difference of months from Dates in Scala?

I have one date in format of date = "2022-07-03 10:09:19"
Need to get difference of months from Today date and time
You can leverage java.time library. Here is a sample code snippet:
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
val dateOld = "2022-07-03 10:09:19".replace(" ", "T")
val dateNew = "2022-11-03 10:09:19".replace(" ", "T")
val l1 = LocalDateTime.parse(dateOld)
val l2 = LocalDateTime.parse(dateNew)
val months = ChronoUnit.MONTHS.between(l1, l2)
For calculating from current time you can use:
val date = "2021-07-03 10:09:19".replace(" ", "T")
val l1 = LocalDateTime.parse(date)
val l3 = LocalDateTime.now()
val months = ChronoUnit.MONTHS.between(l1, l3)
Hope this helps !!
Use ChronoUnit to solve it
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime previousDate = LocalDateTime.parse(date, formatter);
LocalDateTime now = LocalDateTime.now();
long diffMonths = ChronoUnit.MONTHS.between(now, previousDate);
Use java.time if possible
You can parse the datetime String, add a time zone and take the current day or moment in the same time zone. Then you can extract the date and calculate the Period.between those two.
Here's an example in Java:
public static void main(String[] args) {
// example input
String someTime = "2022-07-03 10:09:19";
// prepare a formatter that can parse such a String
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
// prepare the time zone
// (I will use UTC, but the zone depends on the one of the input)
ZoneId utc = ZoneId.of("UTC");
// parse the String, apply the zone and directly extract the date
LocalDate then = LocalDateTime.parse(someTime, dtf)
.atZone(utc)
.toLocalDate();
// get the date of today in the zone
LocalDate today = LocalDate.now(utc);
// calculate the period between the two dates
long months = ChronoUnit.MONTHS.between(then, today);
// prepare some meaningful message to be printed
String msg = String.format(
"The difference in months between %s (then) and %s (today) is %d months",
then, today, months);
// and actually print it
System.out.println(msg);
}
Output:
The difference in months between 2022-07-03 (then) and 2022-08-03 (today) is 1 months
Parse the given date to an instance of java.time.LocalDateTime, then you can get an instance of java.time.Period for the two dates, and from that, you can get the months.
In Java:
final DateTimeFormatter parser = … // An appropriate parser for the given format
final var otherDate = LocalDateTime.parse( dateString, parser );
final var deltaPeriod = Period.between( LocalDateTime.now(), otherDate );
final var result = deltaPeriod.getYears() * 12 + deltaPeriod.getMonths(); // or use Period::toTotalMonths()

How to convert from string format of date (dd/mm/yyyy) to string format of date (yyyy-mm-dd'T'HH:mm:ss.SSS)

I have to convert
"fromTime" : "04-10-2021"`
to
"fromTime" : "2021-10-04T00:00:00.000"
and
"toTime" : "06-10-2021"
to
"toTime" : "2021-10-06T23:59:59.000"
in java . Help please!
Generally speaking, you really want to avoid representing date/time as String where ever possible.
Displaying date/time values to the user should be done in styles that respect their localisation and transmitting date/time values using JSON or XML should use common/standardised formats. This reduces a LOT of issues (don't even get me started)
For example, had I the choice, I would prefer to use ISO_LOCAL_DATE (uuuu-MM-dd) and ISO_LOCAL_DATE_TIME (uuuu-MM-dd'T'HH:mm:ss). I'm already worried about the lack of time zone information 😱
A "simple" approach might be to do something like...
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu.SSS");
LocalDateTime locatDateTime = LocalDate
.parse("04-10-2021", dateFormatter)
.atTime(0, 0, 0, 0);
String dateAndTime = locatDateTime.format(timeFormatter);
System.out.println(dateAndTime);
locatDateTime = LocalDate
.parse("04-10-2021", dateFormatter)
.atTime(23, 59, 59, 0);
dateAndTime = locatDateTime.format(timeFormatter);
System.out.println(dateAndTime);
Basically...
Parse the date value through a DateTimeFormatter using a matching format patten
Convert the LocalDate to a LocalDateTime by passing in the values we want to use
Format the LocalDateTime through a DateTimeFormatter to the desired format
which prints...
04-10-2021T00:00:00.000
06-10-2021T23:59:59.000
See:
The date/time trail
Introduction to the Java 8 Date/Time API
for more details
Now, if all you really want to do, is make it "start of" and "end of" day, you might be able to use...
LocalDateTime startOfDay = LocalDate
.parse("04-10-2021", dateFormatter)
.atStartOfDay();
LocalDateTime endOfDay = LocalDate
.parse("06-10-2021", dateFormatter)
.plusDays(1)
.atStartOfDay()
.minusSeconds(1);
Right about now, I'd be starting a utility class of some kind which had a method which could take a date String (and possibly an optional format) and generate a LocalDate and then another method which could take LocalDate which could convert it to a LocalDateTime at either the startOfDay or endOfDay
You have to do these steps:
create a DateTimeFormatter for dd-MM-yyyy
parse the date with LocalDate.parse with atTime
create a DateTimeFormatter for yyyy-MM-dd'T'HH:mm:ss.SSS
format the date in order to have the final result
public String changeFormatDate(String date, int hour, int minute, int second, int nanoOfSecond) {
DateTimeFormatter formatterFrom = DateTimeFormatter.ofPattern("dd-MM-yyyy"); // 1
LocalDateTime localDateTimeFrom = LocalDate.parse(date, formatterFrom).atTime(hour, minute, second, nanoOfSecond); // 2
DateTimeFormatter formatterTo = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"); // 3
return localDateTimeFrom.format(formatterTo); //4
}
Call example:
String fromTime = changeFormatDate("04-10-2021", 0, 0, 0, 0);
String toTime = changeFormatDate("06-10-2021", 23, 59, 59, 999999999);
Here's an example using java.time:
public static void main(String[] args) {
// input dates / days
String fromDate = "04-10-2021";
String toDate = "06-10-2021";
// prepare the times of day
LocalTime startOfDay = LocalTime.MIN; // 00:00:00.000
LocalTime endOfDay = LocalTime.of(23, 59, 59); // 23:59:59.000
// create an object that takes care of parsing the expected format
DateTimeFormatter customDateParser = DateTimeFormatter.ofPattern("dd-MM-uuuu");
// then parse the dates using the formatter / parser
LocalDate fromDay = LocalDate.parse(fromDate, customDateParser);
LocalDate toDay = LocalDate.parse(toDate, customDateParser);
// then concatenate the parsed dates with the prepared times of day
LocalDateTime fromTime = LocalDateTime.of(fromDay, startOfDay);
LocalDateTime toTime = LocalDateTime.of(toDay, endOfDay);
// finally define a formatter for the String output of the LocalDateTimes
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS");
// and print their toString() methods
System.out.println("from " + fromTime.format(customFormatter)
+ " to " + toTime.format(customFormatter));
}
from 2021-10-04T00:00:00.000 to 2021-10-06T23:59:59.000

java Calendar, sum month, year not changing

How can the year in the output add up according to the month's summation?
int sewa = 10
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String cyear = Integer.toString(year);
int mont = (now.get(Calendar.MONTH) + 1);
String cmont = Integer.toString(mont);
int day = (now.get(Calendar.DATE) );
String cday = Integer.toString(day);
String date = cyear +"/"+cmont+"/"+cday;
Calendar ex = Calendar.getInstance();
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
ex.add(Calendar.MONTH,+sewa);
int exmont = (ex.get(Calendar.MONTH) + 1);
String excmont = Integer.toString(exmont);
int exday = (ex.get(Calendar.DATE) );
String excday = Integer.toString(exday);
String exdate = excyear +"/"+excmont+"/"+excday;
System.out.println(date);
System.out.println("+++++");
System.out.println(exdate);
now : 2018/3/25
+++++ after:2018/1/25
how ouput :2019/1/25
If you are using Java 8 or newer version, please use LocalDate instead of Calendar class. It's very easy to add days, months and years using methods plusDays(), plusMonths() and plusYears(). It's that simple:
LocalDate today = LocalDate.now();
today.plusDays(20);
today.plusMonths(1);
today.plusYears(5);
LocalDate and LocalDateTime were introduced with JSR-310 as much simpler, straightforward and easy to use replacement of Date and Calendar.
However, if you use older version of java, or need to use Date and Calendar for some other reason, you can increase the number of years the same way you did with the months, using
ex.add(Calendar.YEAR, 5);
You capture the year to a variable ...
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
... right before you add 10 months to the calendar ...
ex.add(Calendar.MONTH,+sewa);
... which causes the excyear remains not updated.
To solve it, give the statements a correct order (Get Calendar -> add the months -> get Strings -> print). Or better using SimpleDateFormat:
Calendar ex = Calendar.getInstance();
ex.add(Calendar.MONTH, sewa);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String exdate = sdf.format(ex.getTime());
System.out.println(exdate);
Prints out:
2019/01/25

What is the equivalent of getTime(), which is a method in Date, in joda.time.LocalDate?

I was doing a simple calculation to get the difference between two dates. If I was using a Date class I can do like this:
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
But I couldn't find a method like getTime() in Local date. Is there any way so I can easily get what I am trying to achieve?
I even tried to change my LocalDate object to a temporary date object like this:
LocalDate date=new LocalDate();
Date d=date.toDate();
but the method toDate() isnt working . i.e it says it is not recognized method.(so compile time error) but from what I can see it is in the Documentation
Thank you for your time and of course happy Thanksgiving.
Days.daysBetween() is the answer.
LocalDate now = new LocalDate();
LocalDate past = now.minusDays(300);
int days = Days.daysBetween(past,now).getDays();
Never convert a LocalDate to a Java Date (two completey different beasts) if you are just dealing with dates. A Jodatime Localdate is a true "Calendar date", i.e. , a tuple of {day,month,year} (together with a Gregorian calendar specification), and has nothing to do with "physical time", with seconds, hours, etc. If you need to do dates arithmetic, stick with Localdate and you'll never need to worry about stupid bugs (timezones, DST, etc) which could arise if you dates arithmetic using java Dates.
Try something like this:
LocalDate date = new LocalDate();
Date utilDate = date.toDateTimeAtStartOfDay( timeZone ).toDate( );
or refer to this post
How to convert Joda LocalDate to java.util.Date?
I tested this sample code to find out the difference in days, you can find the difference as per your needs.
Please see http://joda-time.sourceforge.net/key_period.html
LocalDate currentDate = new LocalDate();
LocalDate previousDate = currentDate.minusDays(1);
System.out.println(currentDate);
System.out.println(previousDate);
Period periodDifference = new Period(currentDate, previousDate, PeriodType.days());
System.out.println(periodDifference);
private long diff(Calendar c1, Calendar c2) {
long d1 = c1.getTimeInMillis();
long d2 = c2.getTimeInMillis();
return ((d2 - d1) / (60*60*24*1000));
}
Have not found any equivalents for LocalDate as they are not exact.
But there are several equivalents for LocalDateTime:
LocalDateTime localDateTime = LocalDateTime.now();
long longValue = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
or
long longValue = Timestamp.valueOf(localDateTime).getTime();

how to parse this date

I cant quite figure out what the format should be to parse this date. Its a millisecond value followed by timezone. thx.
// so far tried: "S Z"
// "SSSSSSSSSSS-ZZZZ",
// "SSSSSSSSSSS-Z",
// etc.
Format formatter = new SimpleDateFormat("SSSSSSSSSSSS Z", Locale.CANADA);
// source string looks like this /Date(928164000000-0400)/
String temp = jsonUserObj.getString("DateOfBirth").substring(6, 6+17);
System.err.println("got date="+temp);
Date date = (Date) formatter.parseObject(temp);
You can do it without parser.
String[] parts = new String[]{temp.substring(0, temp.indexOf('-')), temp.substring(temp.indexOf('-') + 1)};
long millis = Long.parseLong(parts[0]);
parts[1] = parts[1].replaceAll("^0*(\\-?[0-9]*)$", "$1");
int timeZone = Integer.parseInt(parts[1]);
int rawOffset = (timeZone / 100) * 3600000 + (timeZone % 100);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
cal.setTimeZone(new SimpleTimeZone(rawOffset, "GMT"));
SimpleDateFormat expects a milliseconds value < 1000, as it expects you would increment seconds, then minutes, etc, for larger values.
You'll need to convert the value first; this post might help: Unix epoch time to Java Date object

Categories