I have to build a program where administration can call onto things of a certain period (choosing a start and end date and the period would be in between those).
Deciding wether a date falls in between the period to actually show the right information I want to convert a string to a date and then to milliseconds.
My code is as follows:
public class Customer
{
// instance variables
private String Consumer;
private Order order;
private String date;
/**
* Fill in the name of the Consumer and the order number.
* Fill in the date/day in dd-MM-yyyy formate please.
*/
public Customer(String Consumer, String date, Order order)
{
// initialise instance variables
this.Consumer = Consumer;
this.order = order;
this.date = date;
}
/**
* Get the startDate
*/
public void getDate()
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date newDate = sdf.parse(date);
}
Now I get the error "incompatible types; You wrote a String where an int was expected.). Isn't it supposed to convert a string? Why does it expect int? The error lies on the "sdf.parse(date);" part.
Any help would be awesome.
Related
I have three classes. My driver class, a Person class, and a Chore class.
I have chores and family members listed in two separate csv files.
The family members file just contains names and dob's (01/01/1901).
So the first thing I want to do is calculate each family member's age based on the year in their dob and get the current year then get the difference of the two. How do I select for just the year in each person's dob and how do I get the current year?
public int currentAge(LocalDate dob, LocalDate currentDate){
if ((dob != null) && (currentDate != null)) {
return Period.between(dob, currentDate).getYears();
} else {
return 0;
}
}
public int getCurrentAge(){
return currentAge;
}
To calculate the age of a person from their birthdate, using Java 8+ Time API, use this method:
public static int getAge(LocalDate dob) {
LocalDate today = LocalDate.now();
int age = today.getYear() - dob.getYear();
if (MonthDay.from(today).isBefore(MonthDay.from(dob)))
age--; // before birthday in current year
return age;
}
Java 8 compatible solution :
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class Demo
{
public static void main(String[] args)
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");
String date = "16/08/2016";
LocalDate dob = LocalDate.parse(date, formatter);
System.out.println(daysBetween(dob));
}
private static long daysBetween(LocalDate dob)
{
return Period
.between(dob,
LocalDate.now())
.getYears();
}
}
We can add a data member in the People for holding the chore information.
class People{
private final String name;
private final LocalDate dob;
private final String gender;
private List<Chores> choresList;
}
You can use the following method or something similar to get the age:
private long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
Read more here or here.
This is my first time looking into the Date Api's i don't understand where i'm going wrong. The Question has been commented out so you can see exactly whats expected.
Could someone please simply explain how to solve/approach this problem?
When i get to the DateUtil class>DayofTheWeek method i attempt to return the LocalDate.DayofTheWeek method using the theDate field which by now has been initialised. but it wont work. It keeps saying 'cannot resolve method'?
public class ChallengeThree {
public static String dayOfWeek(String date) {
/**
*** Returns a String storing the day of the week in all capital letters of the
* given date String
* Complete the implementation of the DateUtil class and use it in this function
* Arguments
* date - a String storing a local date, such as "2000-01-01"
* Examples
* dayOfWeek("2000-01-01") returns "SATURDAY"
*/**
// ====================================
// Do not change the code before this
// CODE1: Write code to return the day of the week of the String date
// using the DateUtil class at the bottom of this file
DateUtil newdates= new DateUtil("2000-01-01");
System.out.println(newdates.dayOfWeek());
// ====================================
// Do not change the code after this
}
// public static void main(String[] args) {
// String theDayOfWeek = dayOfWeek("2000-01-01");
String expected = "SATURDAY";
// Expected output is
// true
// System.out.println(theDayOfWeek == expected);
// }
}
class DateUtil {
LocalDate theDate;
public DateUtil(String date) {
/**
* Initialize the theDate field using the String date argument
* Arguments
* date - a String storing a local date, such as "2000-01-01"
*/
// ====================================
// Do not change the code before this
LocalDate theNewDate = LocalDate.parse(date);
this.theDate=theNewDate;
// ====================================
// Do not change the code after this
}
public String dayOfWeek() {
/**
* Return a String the day of the week represented by theDate
*/
// ====================================
// Do not chDate theDate = new ange the code before this
return LocalDate.of(theDate).getDayOfWeek();
// ====================================
// Do not change the code after this
}
}
You are making this much too complicated.
One problem is that you are thinking in text, using dumb strings rather than smart objects. Do not be passing around the string "2000-01-01", pass around a LocalDate object. Do not pass around the string SATURDAY, pass around the DayOfWeek.SATURDAY object.
LocalDate
.parse(
"2000-01-01"
)
.getDayOfWeek()
.equals(
DayOfWeek.SATURDAY
)
If you insist on using strings against my advice, you can get the name of the DayOfWeek enum object as text by calling toString.
String output = DayOfWeek.SATURDAY.toString() ;
Going the other direction, calling DayOfWeek.valueOf.
DayOfWeek dow = DayOfWeek.valueOf( "SATURDAY" ) ;
Edited
I made a small change in your code (it worked)
DateUtil
class DateUtil {
private LocalDate date;
public DateUtil(LocalDate date) {
this.date = date;
}
public String dayOfWeek() {
return String.valueOf(date.getDayOfWeek());
}
}
ChallengeThree
public class ChallengeThree {
public static void main(String[] args) {
String theDayOfWeek = dayOfWeek("2000-01-01");
System.out.println(theDayOfWeek);
}
public static String dayOfWeek(String date) {
LocalDate localDate = LocalDate.parse(date);
DateUtil dateUtil = new DateUtil(localDate);
return dateUtil.dayOfWeek();
}
}
The other answers are fine. I wanted to go closer to what you asked precisely:
It keeps saying 'cannot resolve method'?
As you have seen, the error message comes in this line:
return LocalDate.of(theDate).getDayOfWeek();
The method it cannot resolve is of(). LocalDate has a couple of overloaded of methods. theDate is already a LocalDate, and as MadProgrammer said in the comment, there is no of method accepting a LocalDate. This is the reason for the error message. BTW, the message I get in my Eclipse says “The method of(int, Month, int) in the type LocalDate is not applicable for the arguments (LocalDate)”.
Since theDate is already a LocalDate, you don’t need that method call at all. Just leave it out and call getDayOfWeek() on theDate directly (I am on purpose leaving to yourself to put it into code; you’re the one supposed to learn from doing this, so you should be the one doing it).
It seems that you are having another problem in that LocalDate.getDayOfWeek() returns a DayOfWeek and your DateUtil.dayOfWeek() is supposed to return a String. You can likely solve it yourself when you get around to it. If not, feel free to follow up in comments.
As a complete aside, for production code I would consider a DateUtil class for this purpose overkill. I understand that this is an assignment, so I have answered it being faithful to the assignment as given.
I am creating a model where i'm trying to store gregorian calendar value in a column, but its showing me error, Calendar Datatype not supported by realmProxcy.
private String alarmName;
private Boolean alarmActive = true;
private Date alarmTime;
private String alarmTonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
private Boolean alarmVibrate = true;
private Calendar cal;
#PrimaryKey
public int alarmid;
Error:(30, 8) error: Type 'java.util.Calendar' of field 'cal' is not supported
how can i store this calendar value and fetch it
If you really need to store a Calendar instance, you can take advantage of it being a Serializable and the possibility of storing byte[] arrays in Realm objects - serialize your Calendar to byte array for storage and deserialize from byte array when accessing data.
Your object would look like this:
class MyRealmObject extends RealmObject {
private String alarmName;
private Boolean alarmActive = true;
private Date alarmTime;
private String alarmTonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
private Boolean alarmVibrate = true;
private byte[] serializedCalendar;
public Calendar getCalendar() {
return deserializeCalendar(serializedCalendar);
}
public void setCalendar(Calendar calendar) {
this.serializedCalendar = serializeCalendar(calendar);
}
}
Refer to this answer on Object<>byte[]serialization/deserialization on how to implement methods:
byte[] serializeCalendar(Calendar c);
Calendar deserializeCalendar(byte[] arr);
Realm database supports only Date class. You have to evaluate your Calendar instance to Date instance.
Calendar cal = Calendar.getInstance();
Date date = cal.getTime(); //save it to realm
From Realm documentation:
Realm supports the following field types: boolean, byte, short, int, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long actually) within Realm. Moreover, subclasses of RealmObject and RealmList are supported to model relationships.
https://realm.io/docs/java/latest/#field-types
Instead of Calendar, use Date from calendar.getTime(), if necessary store Calendar object converter to other type for save and read convert. Example:
public static Calendar toCalendarFromDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
I am storing objects with timestamp in the database(Realm).
public class Met extends RealmObject{
private String name;
private int met;
private long timestamp;
}
I want to show them date wise, like grouping them by date.
Since it is a timestamp and will be different for rows of the same day, I am not able to get it to work.
This comes from the backend and I cannot change it to date.
The only idea I have is to add an extra date field, so that it would be easy to query.
Is there a way to achieve this at the query level without any extra fields?
To query by the same day, you could easily set up a query that queries between the start of the day and the start of the next day.
public class Met extends RealmObject {
private String name;
private int met;
#Index
private long timestamp;
}
And
Date startOfDay = //...get start of day
Date startOfNextDay = //... get start of next day;
RealmResults<Met> mets = realm.where(Met.class)
.greaterThanOrEqualTo(MetFields.TIMESTAMP, startOfDay.getTime())
.lessThan(MetFields.TIMESTAMP, startOfNextDay.getTime())
.findAllSorted(MetFields.TIMESTAMP, Sort.ASCENDING);
i want to use standard class called DateFormat which has subclass SimpleDateFormat TO write a method called convert which returns a String in the form dd.mm.yy: when passed a GregorianCalendar with a specific date
public String convert (Calendar gc) { ... }
For example, when myGC is a GregorianCalendar variable representing the 25th of December 2006, String s = convert(myGC); should set s to the string "25.12.06".
and i'm having trouble to write a convert method on this
public String convert(Calendar c) {
return new SimpleDateFormat("dd.MM.yy").format(c.getTime());
}
Eventually you'll want to store that SimpleDateFormat as a member (for example) if performance becomes a concern.
Why not just use a pattern like this one "dd.MM.yy" in your SimpleDateFormat ?
DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
String myDate = dateFormatter.format(cal.getTime());