Extracting data from a DateTime object - java

I'm working on a method that can tell me if a certain date is within a certain period of dates. My method will have an argument of two DateTime objects; a start date and end date, and will be called by a DateTime object as well.
To play around with it, I've been trying to figure out how to extract the year, month, day , time, from a DateTime object that is being compared to. However I can't figure out how to get it going. I checked the API for DateTime, and the method it has to perform the function I want is monthOfYear().
But when I implement it, it outputs "Property[monthOfYear]".
The API places the method under DateTime.Property but I played around with that too and I'm not getting anywhere.
import org.joda.time.DateTime;
public class Tester implements TesterInterface {
public static void main(String[] args) {
DateTime dateTime1 = new DateTime(2012, 5, 12, 13, 30);
System.out.println(dateTime1.monthOfYear());
}
}

Call getMonthOfYear().
As documented:
Each individual field can be queried in two ways:
getHourOfDay()
hourOfDay().get()

Change
dateTime1.monthOfYear()
to
dateTime1.getMonthOfYear()

Related

Return DayOfTheWeek (as an uppercase string) from a given String input

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.

How to pass a value from a constructor to a setter in another class in JAVA?

Im learning object oriented programming in school right now, and there are some aspects of it I don't quite understand yet. I have a program that creates a database of users with their names, and birthdates. So I have 3 classes: person, PersonProgram(the main), and Date. The Person class has the constructor, setter, and getters for the names and the birth date. The Date class has error checking for proper dates and leap years etc. In the main program I create 5 People, and then give menu options to change and modify the names and dates. So for example, if the user wants to change the name my code looks like this:
System.out.println("Enter new first name:");
people[choice-1].setFirstName(input.next());
and that works and makes sense to me. But I want to know how I can change the date properly? The Date constructor takes 3 integers for the day, year, and month, so in the main program I prompt the user to input the 3 new dateswhich are stored in day, month, year integers. So my understanding is from there I would pass those 3 integers to the Date constructor:
new Date(month, day, year);
What I am confused on is where to go from there. The Date constructor gets the new Date call, and passes it to the setters. How can this newly created date object be passed back to the Person program, so the setter in Person for the birthdate can update the corresponding Person object? If I am not clear on my question please let me know, I figured I could articulate what I am trying to ask without posting all my code.
In your Person class you should have something like this:
public class Person {
private Date birthDate;
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate){
this.birthDate = birthDate;
}
}
And then in you would set the birthDate like:
person[choice-1].setBirthDate(new Date(month,day,year));
Taking into consideration that you are starting with OOP there is an important concept here, Encapsulation, the Person class restricts the free access to its fields, like birthDate, and sets the rules for the interaction with them. As an example you could check if the date is null before assigning it.
public void setBirthDate(Date birthDate){
if(birthDate != null) {
this.birthDate = birthDate;
} else {
//Whatever you wanna do here (throw an Exception, etc, etc)
}
}
Comment Question
Although it would be better to create another question:
Do I have to create an instance of the Date class in my Person class? Or anywhere for that matter?
No, the property/field birthDate is a reference to a Date object which will be stored in memory until no references are left. And it's up to you where to create them, nonetheless there are Creational Patterns, a familiy of Design Patterns that help you with this matter.
is it the birth date in person class of type 'Date'?
if so, you should create an instance of your class Date , do the control that you need and pass it to the constructor or setter of the birth date in the persson instance .
Date birthDate = new Date(month, day, year);
// Some controls
people[choice-1].setBirthDate(birthDate);
Date the_birth_date = new Date(mounth, day, year);
people[choice - 1].setBirthDate(the_birth_date);
You can set it like this: people[choice-1].setBirthday(new Date(month, day, year));. You would have to give the option to select the Person first.

Java current time different values in api

I'm a little confused using the DateTime related class for Java SE 7 and 8 API's, for displaying the current time, I'm reviewing the multiple ways for get the system's current datetime.
My question is: Which one is more accurate for displaying time in millis?
Next is the code snippet, I'm using Java 8 for the reviewing.
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeValidationDemo {
public static void main(String[] args) {
Instant now = Instant.now();
Calendar calendar=Calendar.getInstance();
Date currDate = new Date();
System.out.println("new Date().getTime() = "+currDate.getTime());
System.out.println("System.currentTimeMillis() = "+System.currentTimeMillis());
System.out.println("Instant.now().toEpochMilli() = "+now.toEpochMilli());
System.out.println("Calendar.getInstance().getTimeInMillis() = "+calendar.getTimeInMillis());
System.out.println("Calendar.getInstance().getTime().getTime() = "+calendar.getTime().getTime());
}
}
All the functions that you used in your example return the same value (if launched in the same millisecond) none of them is more accurate.
Once of them is not creating any object, so if you need only to know the current milliseconds since 1/1/1970 use
System.currentTimeMillis()
Instead if you need to have also the equivalent object to store that value or to make additional operations use the object that you need.
For example if you need to pass this value to a function accepting a java.util.Date use java.util.Date (and so on).

Alternative for using set methods when creating a new object

So I am trying to create a program that helps me keep track of my expenses and i have a question to do with how I create my objects.
So far i have been creating my objects like so:
Grocery milk = new Grocery();
milk.setName("Milk");
milk.setCost(2.84);
milk.setDate(30, 12, 2014);
milk.setType("Food");
My grocery class extends this expense class:
public Expense(){}
public Expense(String name, Double cost, Calendar purchaseDate){
name = _name;
cost = _cost;
purchaseDate = _purchaseDate;
}
So far my grocery class only adds another string parameter that i call type, and so here is my question:
Instead of using set methods to set my paramters for each new created object i would like to do it like this:
Grocery milk = new Grocery("Milk", 2.84, ??Date??, "Food")
But the date parameter is a little more complicated than the other parameters that are just of type string and double, is there a way to do what I want or am i better off using the set methods?
Thanks in advance for any help.
You can simply use an Object of type Date
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("16/01/2015");
Grocery milk = new Grocery("Milk", 2.84, date, "Food")
Alternatives include using a Calendar object (which has more flexible/powerful date manipulation methods), or just storing your date as a String.
As for deciding whether you should use setX() methods or using a comprehensive constructor, unless there is a reason not to you can just have both available, and just use the most suitable at any one time.
Further reading:
Official Java Date & Time tutorials
Official Java Calendar tutorials

What's the difference between setTime(...) and setTimestamp(...) in Hibernate Query?

I wonder why the setTime method behaves exactly like setDate, date without time, or instead to set the time on 2014-07-01 13:21:01 it is set on 2014-07-01 00:00:00 ?!?!
Is setTime deprecated?
Should I use setTimestamp???
Databases other than Oracle actually do distinguish between three different datatypes:
DATE only date, no time
TIME only time of the day, no date
TIMESTAMP both, date & time.
JDBC tries to abstract standard SQL concepts and the above three datatypes are defined by ANSI SQL and thus JDBC needs to support them.
As Oracle's date always includes the time, you have to use setTimestamp() otherwise the time is lost when you store it in the database.
setTime() Method :
The java.util.Calendar.setTime(Date) method sets Calendar's time with the given Date.
Following is the declaration for java.util.Calendar.setTime() method
public final void setTime(Date date)
This method does not return a value.
Example :
The following example shows the usage of java.util.calendar.setTime() method.
package com.tutorialspoint;
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create a calendar
Calendar cal = Calendar.getInstance();
// get the current time
System.out.println("Current time is :" + cal.getTime());
// create new date and set it
Date date = new Date(95, 10, 10);
cal.setTime(date);
// print the new time
System.out.println("After setting Time: " + cal.getTime());
}
}
SetTimestamp Method :
Sets the designated parameter to the given timestamp and calendar values.
Syntax
public void setTimestamp(java.lang.String sCol,
java.sql.Timestamp x,
java.util.Calendar c)

Categories

Resources