This question already has answers here:
Get first date of current month in java
(11 answers)
Closed 1 year ago.
Im working on a project that visually displays statistical data from each month and week and i dont know how to elegantly renew the dates of each week and month.
For example, i want to display this months data. I have to make two date variables in Java. The first one being 1.5.2021 and the second one being todays date. I dont know how to elegantly set the first variable to 1.x.xxxx without making a string out of the current date first and then cuting it, doing some numerics with it and merging it back together to 1.5.2021.
Same goes for weekly statistics where i need the Monday date and the Sunday date, for example today being Monday 10.5.2021 and the end on 17.5.2021.
So my idea is to get current date to string format, slice it, convert it to int, calculate the desired dates and the put it back to string(no need to go back to datetype since its gonna be used for querying).
Well, you should definitely take a look at the classes within the java.time package.
In your case, your current date could be a LocalDate instance, for example with the following line:
LocalDate.of(2021, 5, 1);
And then you could just use the withDayOfMonth method to get a new LocalDate instance with the day of the month set to 1:
LocalDate currentDate = LocalDate.now();
LocalDate firstOfMonth = currentDate.withDayOfMonth(1);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on Selenium Java, I need to get the following date format without the time, as a string in selenium java to validate whether it is up to date with the published date. I used getText() method from the website by splitting from the time and date. Is there any other best ways rather than this solution!
java.time
Edit: I have added more explanation and more code lines.
There’s a little challenge in the fact that the string on the website does not include year. One simple way to handle it is:
ZoneId websiteTimeZone = ZoneId.of("America/Lower_Princes");
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("dd-MMM HH:mm", Locale.ENGLISH);
String stringFromWebsite = "06-Feb 06:37";
MonthDay today = MonthDay.now(websiteTimeZone);
System.out.println("Today is " + today);
MonthDay date = MonthDay.parse(stringFromWebsite, formatter);
System.out.println("Date from website is " + date);
if (date.equals(today)) {
System.out.println("It’s up to date");
} else {
System.out.println("It’s *NOT* up to date");
}
When I ran today (March 12), the snippet printed:
Today is --03-12
Date from website is --02-06
It’s *NOT* up to date
A MonthDay is a month and day of month without year. The advantage of using this class is we don’t need concern ourselves with year. A possible drawback is we can’t compare two such objects determine which one is before or after the other one. Such a comparison would require knowing the year of each one.
We need to know the time zone that the website uses since it is never the same date everywhere on Earth. Please insert the correct one where I put America/Lower_Princes.
I am parsing the string from the website into a MonthDay using a DateTimeFormatter with format pattern dd-MMM HH:mm since lower case d is for day of month, M is for month, H for hour of day and lower case m for minut of the hour. Since I am parsing into a MonthDay, the time is ignored (only its syntax still checked). In the print --03-12 means March 12 and --02-06 similarly February 6 (the date from the website). Since they are not the same, the code prints that the website is not up to date.
A more advanced solution might check if the date is a few days before or after today’s date and/or also look at the time.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Stack Overflow question How do I simply parse a date without a year specified?
You can use selenium's getText(), in order to acquire the value as a String.
Afterwards you can use Java's DateTimeFormatter, to parse this date, and transform it to the format you want
Could someone please help me in finding from datepicker first and last day of previous month.
Achieved to pickup current date and 1st of current month, with following:
// Choose today's date
String today = LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));
driver.findElement(By.xpath("//*[#id=\"viewPeriodStart\"]")).clear();
driver.findElement(By.xpath("//*[#id=\"viewPeriodStart\"]")).sendKeys(today);
//Choose first of a month
String firstDayinMOnth = LocalDate.now().format(DateTimeFormatter.ofPattern("01/MM-YYYY"));
driver.findElement(By.xpath("//*[#id=\"viewPeriodEnd\"]")).clear();
driver.findElement(By.xpath("//*[#id=\"viewPeriodEnd\"]")).sendKeys(firstDayinMOnth + Keys.ENTER);
Thread.sleep(8000);
driver.findElement(By.xpath("//*[#id=\"calenderShowHide\"]/div/input[3]")).click();
But have no idea how to create 1st and last of previous month.
Thank you in advance
Solved, after a bit of Googling & checking:
String lastDay = LocalDate.now().withDayOfMonth(1).minusDays(1).format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));
String firstDay = LocalDate.now().withDayOfMonth(1).minusDays(1).withDayOfMonth(1).format(DateTimeFormatter.ofPattern("dd/MM-YYYY"));
These points were not what you asked, but I believe they are still helpful suggestions for you.
Consider half-open intervals.
Read LocalDate.now() only once for consistency.
Give your desired time zone.
Don’t use uppercase YYYY in your format pattern string.
Half-open: It’s natural to think of the days of a month as being from the first of the month to the last day of the month inclusive. However, a standard handling would go from the first of the month inclusive to the first of the next month exclusive. It’s still the same days, only a different representation. Particularly when you handle successive months this gives simplicity and prevents errors: when you have the first of this month, you don’t also need the last of the previous month. And there’s no way you could make a gap between the two periods by mistake.
Read today’s date only once. If your code happens to run across midnight, you may accept that you cannot control whether it uses the date from before 0:00 or the date after, but you want to make sure it doesn’t use both for the different date calculations, or you risk inconsistent dates, like all the dates belonging to the same month rather than last month and this month.
Give a time zone: It is never the same date in all time zones on Earth. So a time zone is needed for determining today’s date or just current month. Make that explicit. Even if you want ZoneId.systemDefault(), write that to force yourself into making a conscious decision and to tell the reader that you have done so.
LocalDate today = LocalDate.now(ZoneId.of("Europe/Belgrade"));
LocalDate firstDayOfCurrentMonth = today.withDayOfMonth(1);
LocalDate lastDayOfCurrentMonth = today.with(TemporalAdjusters.lastDayOfMonth());
YearMonth lastMonth = YearMonth.of(today.getYear(), today.getMonth())
.minusMonths(1);
LocalDate firstDayOfLastMonth = lastMonth.atDay(1);
LocalDate lastDayOfLastMonth = lastMonth.atEndOfMonth();
A YearMonth is a month in the calendar like April 1940 or February 2018. A year and a month. I am deliberately being a bit inconsistent in the code. In production code you would probably want to handle either this and last month through YearMonth objects or none of them. But I am showing you both options so you can make your pick. Use YearMonth.now(ZoneId) if you want current month.
Final point: YYYY in the format pattern string. Here’s a correct version of your formatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM-uuuu");
If instead of today I run my code next January and use a formatter with uppercase YYYY, I get the previous month as 01/12-2018 through 31/12-2019. It should have been 31/12-2018, but that date belongs to week 1 of 2019, which is what YYYY gives you. Instead use uuuu or lowercase yyyy.
This question already has answers here:
How would you represent date of birth in your java model?
(6 answers)
Closed 6 years ago.
I am currently making an App on Android where a user will Register their details.
In my database I have DOB as a Date type.
Would I declare DOB in Java as a String? Double? Int? I'm confused how I will go about this so it satisfies the database's Date format.
Any help will be great!
A java.time.LocalDate (or logically-equivalent classes likes org.joda.time.LocalDate) is the best way to represent a date-of-birth (DOB) in Java code.
Note that DOB is not well-modelled as a java.sql.Date, or a java.util.Date: these model instants in time, not timezone-independent dates.
Whilst one is clearly born at some instant in time, this is not how we, societally, report when we are born. Consider that two children born at the same instant in different time zones might actually have different dates of birth - if the child in NYC is born at 2AM on 1st April, the child born in LA is born at 10PM on 31st March.
Neither child's date of birth changes when they travel to the other city (or anywhere else, of course). As such, if you store the instant of birth, you also need to store the time zone of birth in order to correctly interpret that instant as the date of birth.
But storing an instant and a timezone is inconvenient: not only is it more data to store, but also it is difficult to interpret it "by eye" (e.g. it's hard to tell what date (1459438541000, America/Los_Angeles) refers to). It is much easier to store and interpret the year, month and day directly: (2016, 3, 31).
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.
I'm working on a project that is going to require our own custom calendar view. I've been trying to figure out the best way to approach this.
I was considering possibly using a Master xml file that will define the basic layout of the calendar, and then use a secondary xml file, and nest it into each cell of the calendar for each day as an array of objects.
Not exactly sure if this is possible, or if this would be the best way to approach this problem?
Cheers
I recently created a Month layout, using TableLayout.
I took into consideration that you will need 6x7 days for a month to be able to handle every possible situation. (First day of the month being a sunday, last day of the month being a monday etc.)
Based on a given date (lets say 3rd of August) I calculate the first day to be shown
date = 3rd of August
firstDate = first day of month based on date
while( firstDate is not a monday )
firstDate = present date
I then calculate the last day to be shown:
lastDate = last day of month based on date
while( lastDate is not a Sunday )
lastDay = following date
This gives me an interval of dates from firstDate to lastDate
Then I programaticly create 6 TableRow's in which there are 7 days - a TextView or whatever. It could just be declared in an XML-file if you don't want to create too much layout on the fly. One thing to remember is to set the layout_weight for the TextViews so that they are all equally big/small to create a nice grid.
If what you need is more like a Day- or Weeklayout the challenge is a little tougher.
Android has a util for doing all the math to find the days in a month. I guess using a gridview with android.util.MonthDisplayHelper should work.