How to customize the TemporalAdjusters in Java 8? - datetime

I am working with Java 8 Date and Time utility. I am using the TemporalAdjuster interface and the implementations found in TemporalAdjusters to manipulate the calculations for a specific day or date.
My requirement is to calculate the day after 3 month and 2 days.
For example, today is 6th of Decemeber (i.e 2016-12-06 in YYYY-MM-DD) and after 3 months and 2 days, the date would be 8th of March, 2017 (i.e. 2017-03-08 in YYYY-MM-DD).
I tried two ways of doing this using the Date and Time utility as follows:
//First
LocalDate dayAfter3MonthsAnd2Days = LocalDate
.now()
.with(firstDayOfNextMonth()).plusMonths(2).plusDays(2);
//Second
LocalDate dayAfter3MonthsAnd2Days = LocalDate
.now()
.with(firstDayOfMonth()).plusMonths(3).plusDays(2);
Both of them returns the date as 3rd of March, 2017 (i.e. 2017-03-03) as follows:
dayAfter3MonthsAnd2Days = 2017-03-03
Is there any way i can customize the TemporalAdjusters and get the desired output? Or any other alternate to achieve the goal?

I found out that i can simply use the following:
LocalDate dayAfter3MonthsAnd2DaysNew = LocalDate
.now()
.plusMonths(3)
.plusDays(2);
Alongwith that, i can also use the custom TemporalAdjuster which uses the above same process to do manipulations as follows:
TemporalAdjuster ta = TemporalAdjusters.ofDateAdjuster(
(LocalDate d) -> d.plusMonths(3).plusDays(2));
LocalDate dayAfter3MonthsAnd2DaysCustom = LocalDate
.now()
.with(ta);
Although the previous way is simpler, but we can use more custom proceedings using ofDateAdjuster method of TemporalAdjuster.

Related

Date and time format in JavaFX

I'm currently working on a JavaFX project and having issues while displaying current date in a text area.
I set the date and time format by using the following code:
SimpleDateFormat Date = new SimpleDateFormat("dd/MM/yy hh/mm");
Date date = new Date();
For example, I want the current date and time to be displayed as 15/05/2021 15:03 but the textarea shows this:
SAT May 15 15:03:21 PDT 2021
Is there anyway to set date format to "dd/MM/yy hh/mm"?
*NOTE: I imported both java.text.SimpleDateFormat and java.util.Date.
The java.util.Date, java.util.Calendar,
and java.text.SimpleDateFormat classes were rushed too quickly when
Java first launched and evolved. The classes were not well designed or
implemented. Improvements were attempted, thus the deprecations you’ve
found. Unfortunately the attempts at improvement largely failed. You
should avoid these classes altogether. They are supplanted in Java 8
by new classes (Basil Bourque).
Use this instead:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yy hh:mm");
TextArea textArea = new TextArea(formatter.format(now));

Java how to add time and date

Using JDK 1.8
I have Time in ms for a day (not since 1970) and I have a Date how do I add the two and create a datetime.
Thanks
Tried #Kikos soln does not produce correct result:
Somehow my orig time 930 hrs in this case changes to 9:40, the orig date itself should not have any time gets time (??) - so the addition math fails.
String testdate = "2015/10/25";
Date date = new SimpleDateFormat("yyyy/mm/dd").parse(testdate);
String timehrs= "930";
long ltime = Long.parseLong("930");
long hoursAsSeconds = (ltime / 100) * 60 * 60;
long minsAsSeconds = (ltime % 100) * 60;
long secondsOfDay = hoursAsSeconds + minsAsSeconds;
System.out.println("testdate : "+ testdate +", timehrs: "+timehrs+" ,secondsOfDay: "+secondsOfDay);
System.out.println("Orig Date time formatted: "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date));
Date dt = new Date(date.getTime() + secondsOfDay*1000);
System.out.println("New Date : "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(dt);
testdate : 2015/10/25, timehrs: 930, secondsOfDay: 34200
Orig Date time formatted: 2015-10-25 12:10:00
New Date : 2015-40-25 09:40:00
Expected : 2015-10-25 09:30:00
Based on below by #Basil Bourque
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( secondsOfDay*1000 );
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );
ZoneId z = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
System.out.println("ZonedDateTime zdt: "+ zdt);
ZonedDateTime zdt: 2015-10-25T09:30-07:00[America/Los_Angeles]
This is the correct answer: 2015-10-25T09:30
Question is convoluted
You say you have time of day as a count of milliseconds since midnight (apparently). Yet 930 would mean the time 00:00:00.930, not 09:30:00 as shown in your example data. I will follow your text rather than your example data.
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. Forget you ever heard of java.util.Date and .Calendar.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
ISO 8601
The java.time classes use the ISO 8601 standard by default when parsing/generating strings representing date-time values. To make your input string standard, replace those slash characters with hyphens.
String input = "2015/10/25".replace( "/" , "-" );
LocalDate ld = LocalDate.parse( input );
By the way, this whole scheme you have been assigned is awkward, error-prone, and needlessly complicated. To serialize a date-time value for communication between systems, use the ISO 8601 string formats.
LocalTime
You say you have a count of milliseconds to represent the time of day as a count from midnight.
The LocalTime class offers factory methods to instantiate based on a duration of whole seconds and of nanoseconds. To get nanoseconds, simply multiply your milliseconds by one thousand. Better yet, let the TimeUnit enum do the work and make your code more self-documenting.
long millisOfDay = Long.parseLong( "930" );
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( millisOfDay ); // Same effect as: ( millisOfDay * 1_000L )
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );
ZonedDateTime
Now combine these two Local… objects along with a time zone to determine a point on the timeline. Was this date and time meant to be a moment in Montréal Québec, Paris France, Kolkata India, or Aukland New Zealand?
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
See live code in IdeOne.com.
ld.toString(): 2015-10-25
lt.toString(): 00:00:00.930
zdt.toString(): 2015-10-25T00:00:00.930+13:00[Pacific/Auckland]
LocalDateTime
If your data came with no information about time zone, and you cannot safely assume the intended time zone by your business scenario, you are left with no better option than combining into a LocalDateTime object. But keep in mind that this value is ambiguous. This value is not a point on the timeline. This value represents potential points on the timeline which can only be determined with a time zone assigned for ZonedDateTime or a offset-from-UTC assigned for OffsetDateTime.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
something like:
Date dt = new Date(System.currentTimeMillis() + ms);
or
Date otherDate(....);
Date dt = new Date(otherDate.getTime() + ms);

Flex Date related Functions

I need to calculate a start date as 01- 01- 2013 when my end date is 31-12-2012 using Flex Date Functions'.
I assume you want to add a certain amount of days (1 in your example) to an existing date? You can do this by creating a new date based on the time of the other date + the difference:
Example:
var numMillisecondsInOneDay:Number = 24*60*60*1000;
var startDate:Date = new Date(endDate.getTime() + numMillisecondsInOneDay);
FYI: The AS3Commons-Lang project contains a DateUtils class that offers a set of Date manipulation methods.

How to save the Date as DD/MM/YYYY format in SQLITE Flex AIR application

i am doing a flex Adobe AIR Application with SQLITE Data base,in that i want to save Date in the following format DD/MM/YYYY, but in my SQLITE TABLE i gave the data type is DATE so it saved as Sun Dec 2 00:00:00 GMT+0530 2012 in this format.
why i want to save in specific format.i have two date fields START DATE and END DATE.Once i select the End DATE date field i have to count the days between them automatically.any ideas for DD/MM/YYYY format and counting the date in between the dates.
This is my code:
[Bindable] private var date1:Date;
[Bindable] private var date2:Date;
[Bindable] private var Totaldays:String;
protected function modEndDate_creationCompleteHandler(event:FlexEvent):void
{
formatter.formatString= "DD-MM-YYYY";
date1=formatter.format(newStartdate.selectedDate);
date2=formatter.format(newEndDate.selectedDate);
**Totaldays=Math.floor(Math.abs(date1 - date2)/ (24 * 60 * 60 * 1000))**
}
The error is:
Multiple markers at this line:
-1067: Implicit coercion of a value of type Date to an unrelated type Number.
-1067: Implicit coercion of a value of type Number to an unrelated type String.
Looking for help.Thanks in Advance
Regards,
Venkatesan
Save in compatible format. Format dates in GUI as you like. Look here to calculate days between: ActionScript 3.0 + Calculate timespan between two dates?

Groovy - idiomatic way of coding The Last Weekday - First of Month

What is the Groovy idiomatic way of asking for the last past weekday (ex. Monday)?
(or current week, the first day of the week)?
Also is there something similar for asking for the current month, the first of month?
static Date firstDayInWeek(Date day) {
day.clearTime()
return day - day.calendarDate.dayOfWeek
}
A year ago, I wrote a simple DSL for calculating dates, this allows you to do:
def mondayInJuly = new DateDSL().with {
first.monday.in.july( 2011 )
}
which sets mondayInJuly to be a Date object representing
Mon Jul 04 00:00:00 UTC 2011
I need to update the script to allow you to use Groovy 1.8's more lenient parser
As you mention DateTime in tags, I suggest JodaTime is OK. So, we do:
def lastMonday =
new DateTime().withDayOfWeek(DateTimeConstants.MONDAY).minusWeeks(1)
def firstThisMoth = new DateTime().withDayOfMonth(1)

Resources