How to get milliseconds from a date picker? - java

In my project I am saving milliseconds in a sqllite databse, by default I am saving
System.currentTimeMillis()
in the database, but there is an option for the user to select previous date from a date picker? But what sould I save then when user selects a previous or up comming days from the date picker? How can I get that day as a long(milliseconds) format?

Create a Calender instance and set the date you want. Then call calendar.getTimeInMillis();. See the answer of this previous SO question for more information.
EDIT To set the calendar date you can use something like this:
//Lets suppose you have a DatePicker instance called datePicker
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
cal.set(Calendar.MONTH, datePicker.getMonth());
cal.set(Calendar.YEAR, datePicker.getYear());
See the Calendar class for more information.

I was looking for a similar solution for a javase scenario when I came across this answer. I made a little modification to Angelo's answer to make my own case work, and it gave me exactly what I was looking for. To make things a little more interesting, I created a method that can be reused.
class Controller {
public static Calendar cal = Calendar.getInstance();
public static long getEpoch_fromDatePicker( DatePicker datePicker ) {
Controller.cal.set(Calendar.DAY_OF_MONTH, datePicker.getValue().getDayOfMonth() );
Controller.cal.set(Calendar.MONTH, datePicker.getValue().getMonthValue() );
Controller.cal.set(Calendar.YEAR, datePicker.getValue().getYear() );
return Controller.cal.getTimeInMillis() /1000;
}
}
Someone might find this useful

Related

Java date handling in improper format

Firstly, I'm a C# dev learning Java. I'm converting a program I wrote in C# as an exercise and am having problems with parsing a date being submitted from an html form. The form is sent as an email and the java program reads the emails and parses the body. I have a drop down calendar for my peeps to select a date from but there's always some jerk who has to type it in and mess everything up. Currently I am doing this in my code:
public void SetDatePlayed(String datePlayed)
{
this.datePlayed = LocalDate.parse(datePlayed);
}
datePlayed being passed in is a string usually formatted as yyyy-MM-dd but of course someone typed in 3/7 instead of using the calendar drop down on the form. this.datePlayed is a LocalDate. In C# I would just end up with a date that assumed 2020 for the year - no problem. LocalDate really wants it in the yyyy-MM-dd format and I don't know what the best practice here is with Java. I've been googling it all morning and haven't come across this as being an issue for anyone else. I don't care if I'm using LocalDate but I do need it to be a date datatype so I can do date checks, sorts, searches, etc later on.
You can use DateTimeFormatterBuilder and parseDefaulting() to supply default value for the year.
Building on the answer by Sweeper, it can be done like this:
static LocalDate parseLoosely(String text) {
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.appendPattern("[uuuu-M-d][M/d/uuuu][M/d]")
.parseDefaulting(ChronoField.YEAR, Year.now().getValue())
.toFormatter();
return LocalDate.parse(text, fmt);
}
Warning: Do not cache the formatter in e.g. a static field, since it snapshots the year, if the program might be running across New Year's Eve, which a webapp would, unless you add logic to make the cache auto-refresh on year change.
Test
System.out.println(parseLoosely("2019-04-07"));
System.out.println(parseLoosely("2019-4-7"));
System.out.println(parseLoosely("4/7/2019"));
System.out.println(parseLoosely("4/7"));
Output
2019-04-07
2019-04-07
2019-04-07
2020-04-07
I see two possible interpretations of your question. I'm not sure which one it is, so I'll answer both.
How do I parse a date string in a format that has no year, such as M/d (3/7), to a LocalDate?
You don't. A LocalDate by definition must have year, month, and day. If you only have a month and a day, that's a MonthDay:
MonthDay md = MonthDay.parse("3/7", DateTimeFormatter.ofPattern("M/d"));
If you want the current year added to it, you can do it later:
LocalDate ld = md.atYear(Year.now(/*optionally insert time zone*/).getValue());
How do I handle both yyyy-MM-dd and M/d patterns?
Here's one way: create a DateTimeFormatter that recognises both patterns, parse the string to a TemporalAccessor, check if the TemporalAccessor supports the "year" field:
TemporalAccessor ta = DateTimeFormatter.ofPattern("[M/d][yyyy-MM-dd]").parse("3/7");
if (ta.isSupported(ChronoField.YEAR_OF_ERA)) { // yyyy-MM-dd
LocalDate ld = LocalDate.from(ta);
} else if (ta.isSupported(ChronoField.MONTH_OF_YEAR)) { // M/d
MonthDay md = MonthDay.from(ta);
} else {
// user has entered an empty string, handle error...
}

java- How to add 7 days to a default date?

I have a current date in Java like below:
String currentDate = CoreUtil.parseDate(new Date());
This returns the date for today in the form 2019-03-26.
I declared another date so that it should automatically add 7 days to the current date like below:
String defaultendDate=CoreUtil.parseDate(new Date()); + 7 days //example
So the defaultEnddate should be 2019-04-03
How would I accomplish this as I don't want to use any simple date formatter?
Also, I would like to store the date as it is in String for reasons and secondly, I only want date, not the time. I am not using Java 8 as well, so I can't really use LocalDate library here.
LocalDate is perfect for this job:
LocalDate.now().plusDays(7);
You can get your string representation with
.format(DateTimeFormatter.ISO_DATE);
If you're not able to use Java 8, then you have a few options:
Use the ThreeTen-Backport, which backports most functionality of the Java 8 JSR-310 API, normally available in the java.time package. See here for details. This package is available in Maven Central.
You can also use Joda Time. The peculiar thing is that these two projects have almost the same layout of their websites.
If you're otherwise not able to use ThreeTen-Backport or Joda Time, you can use this:
Calendar c = Gregorian​Calendar.getInstance();
c.add(Calendar.DATE, 7);
String s = new Simple​Date​Format("yyyy-MM-dd")
.format(c.getTime());
Warning
Many things are wrong with the old Date and Time API, see here. Use this only if you have no other option.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 7);
Date defaultEndDate = cal.getTime();
Something like
LocalDate.now().plusWeeks(1);
would also do the cause.
Please, bare in mind using Java 8 Date/Time API for any operations with dates and times. as it addresses shortcomings of old Date and Calendar regarding thread safety, code design, time-zone logic and other.
UPDATE:
If you must use old Date/Time API, following code would suffice:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("Adding seven days: " + calendar.getTime());
date = calendar.getTime();
//your code
String currentDate = CoreUtil.parseDate(new Date());
*
String dt = new SimpleDateFormat("yyyy.MM.dd").format(new Date()); // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
System.out.println(dt);
*
Use java.util.Date try this one

Issue populating current date into the web form using selenium by reading from excel sheet

I have the code of getting current date, But i need Set current date -1 i.e yesterday's Date.
However my main issue comes how could I populate in to the webform using selenium , as i do have to read surname, forename, DOB and medicalreport (here i need to fill it with yesterday date in ddMMyyyy format) reads from Excel File.
Here the is java code to get the Yesterday's Date with format ddMMyyyy.
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
Hope this help you.Let me know if this work.

how to add days to java simple date format

How should I add 120 days to my current date which I got using simple date format?
I have seen few posts about it but couldn't get it to work,
My code is below:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
//get current date time with Date()
Date date = new Date();
Do I need to use the Calendar library or can I just do it with simple date format?
Basically, you can simple use a Calendar which has the capacity to automatically roll the various fields of a date based on the changes to a single field, for example...
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 120);
date = cal.getTime();
Take a closer look at Calendar for more details.
Yes, there is a way to do this using Joda Time, but I could type this example quicker ;)
Update with JodaTime example
The following is an example using JodaTime. You could parse the String value directly using JodaTime, but since you've already done that, I've not bothered...
Date date = ...;
DateTime dt = new DateTime(date);
dt = dt.plusDays(120);
date = dt.toDate();
I would suggest you use Joda DateTime if possible. The advantage is it handles TimeZone very gracefully. Here's how to add days:
DateTime added = dt.plusDays(120);
Reference:
http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html#plusDays(int)

Set first day of week in JDateChooser

I need some help to be able to set the first day of week from Sunday to Monday (change SMTWTFS to MTWTFSS) in com.toedter.calendar.JDateChooser, I tried like this with no result, I'm using version 1.3.3 of JDateChooser:
JDateChooser dateChooser = new JDateChooser(new Date());
dateChooser.getCalendar().setFirstDayOfWeek(Calendar.MONDAY);
Following the conventions of proper getter implementation, getCalendar() probably returns a copy of the calendar used. Therefore your call to setFirstDayOfWeek() is on an object that is not the calendar object of your JDateChooser.
I can't seem to find the documentation for JDateChooser 1.3.3, but if setCalendar() exists, this should work:
Calendar c = dateChooser.getCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
dateChooser.setCalendar(c);

Categories