Static Variables Not Affecting Other Objects in Java Calendar Class - java

Since the Calendar class in Java has static data fields such as DATE, why don't the other objects change when the static field is modified?
I have made two different Gregorian Calendars and thought static data fields changed the value for all of the objects instead of one.
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TEST {
public static void main(String[] args) {
GregorianCalendar cal = new GregorianCalendar();
System.out.println(cal.get(Calendar.DATE));
GregorianCalendar cal2 = new GregorianCalendar();
cal2.set(Calendar.DATE, 12);
System.out.println(cal2.get(Calendar.DATE));
System.out.println(cal.get(Calendar.DATE));
}
}

Calendar.DATE is not a static field, it's a static variable that's used to reference which type of value you want to set/get in a specific Calendar instance.
If you look at the actual source code of java.util.Calendar you would see that it has an internal int array that holds all the values, i.e. day, month, year, etc.
Calendar.DATE is just a nice way of referencing the fifth element of that array.
Declaration of member in the Java 8 source code.
/**
* Field number for <code>get</code> and <code>set</code> indicating the
* day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
* The first day of the month has value 1.
*
* #see #DAY_OF_MONTH
*/
public final static int DATE = 5;

The Answer by rorschach is correct and should be accepted.
Also, you are using old date-time classes that have proven to be poorly designed, confusing, and troublesome. Avoid them. They have been supplanted by the java.time classes.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate nextWeek = today.plusWeeks( 1 );
LocalDate midMonth = today.withDayOfMonth( 15 );
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate secondTuesdayOfThisMonth = today.with( TemporalAdjusters.dayOfWeekInMonth( 2 , DayOfWeek.TUESDAY ) );

Related

call staic method with instance class (LocalDate

my question is about the class LocalDate have a static method of that return a new instance of the classe example
LocalDate local = LocalDate.of(2019,9,21);
the probleme is that i can't call the method of with instance class localDate
(local.of(..) !!!!!!!!!???)
thanks for help :)
The static method LocalDate of(int year, int month, int dayOfMonth) Obtains an instance of LocalDate from a year, month and day. so you must use a reference of a LocalDate object to store the returned instance.
LocalDate local = LocalDate.of(2019,9,21);

Java Custom Data Type

I wanted to create a class with a custom data type that returns the class object. Consider a class Custom:
public class Custom {
// Some fields.
public Custom(String custom) {
// Some Text.
}
// Some Methods.
public void customMethod() {
// Some Code.
}
}
Now, consider a second class TestCustom:
public class TestCustom {
public static void main(String[] args) {
Custom custom = new Custom("Custom");
System.out.println(custom); // This should print "Custom"
custom.customMethod(); // This should perform the action
}
}
So, the question how to get the value custom on instantiating an object instead of memory location. Like what I get is:
Custom#279f2327
The java.util.Date class returns the current date. This can be seen as the constructor for the class is
public Date() {
this(System.currentTimeMillis());
}
For example, the following code would print out the current date:
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
System.out.println(format.format(date));
The Answer by ML72 is correct and should be accepted. The java.util.Date constructor captures the current moment in UTC.
java.time
The java.util.Date class is terrible, for many reasons. That class is now legacy, supplanted years ago but the java.time classes as of the adoption of JSR 310.
The java.time classes avoid constructors, instead using factory methods.
The replacement for java.util.Date is java.time.Instant. To capture the current moment in UTC, call the class method .now().
Instant instant = Instant.now() ;
If you want the current moment as seen through the wall-clock time used by the people of a particular region (a time zone), use ZoneId to get a ZonedDateTime object. Notice again the factory method rather than a constructor.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Adjust to UTC by extracting an Instant.
Instant instant = zdt.toInstant() ;
Override the toString() method, as it is automatically invoked when you try to display an object:
Add a field. For example;
private String value;
In the constructor, add the following code:
value = custom;
this will assign a value passed to the constructor as a parameter, to the value field.
And finally override the toString() method as follows:
#Override
public String toString() {
return value;
}
Now, when you display the value of the custom object, the overridden toString() method will be invoked and the argument will be displayed instead of the memory address. Whereas methods of the object will work as they are programmed to work. There is nothing to be changed with them.

In an enum class, how can one cast values as dates?

In an enum class, how can one cast a value as the type java.util.date?
The enum still has to have a name.
I have tried:
ENUM_OPTION1(Date(10000000000L))
But I got an error saying that
"Symbol Date(long) wasn't recognized", even though I imported the class at the top of my file.
new Date( … )
Use new to instantiate a java.util.Date.
ENUM_OPTION1( new Date( 10_000_000_000L ) )
FYI, java.util.Date is a terrible class that was supplanted years ago by the java.time classes, specifically Instant.
Full example
Add a constructor on your enum. On each instance of the enum you declare, call the constructor. To that constructor, pass the specific date. See tutorial by Oracle.
public enum History {
US_DECLARATION_OF_INDEPENDENCE( LocalDate.of( 1776 , Month.July , 4 ) ) ,
US_CONSTITIUTION_APPROVED( LocalDate.of( 1787 , 9 , 17 ) )
;
private LocalDate localDate ;
// Constructor
public History( LocalDate ld ) {
Objects.requireNonNull( ld ) ;
this.localDate = ld ;
}
// Getter
public LocalDate getLocalDate() {
return this.localDate ;
}
}
To use this enum, call the instance method on one of the named constant instances.
LocalDate ld = History.US_DECLARATION_OF_INDEPENDENCE.getLocalDate() ;

Java 8 best way to parse text date to millisecond timestamp

I want to create a Java class with thread-safe static methods to parse dates. I understand that some of the Java 7 (and earlier) date time classes are not thread-safe. What is the best thread-safe implementation in Java 8 of this functionality:
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
In Java 7 and earlier, you would do this:
public class DateUtil {
public static long getTimestamp(String text) {
DateFormat df = new SimpleDateFormat("M/d/yyyy");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
long timestamp = df.parse(text).getTime();
return timestamp;
}
}
But instead of creating a new instance of DateFormat for every call, I want to share a single static instance for all calls to this static getTimestamp method. My understanding is that this is not thread-safe.
One key requirement is that the text I want to parse has a short date like "5/16/2008" without HH:mm:ss resolution.
I also don't want to use a third party library like Joda-Time, but rather only standard Java 8 classes.
Here's a version of your code refactored to use the java.time.* package in Java 8. It uses a static final formatter instance, which is thread-safe and immutable, unlike java.text.SimpleDateFormat.
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()).getTime();
}
}
You can use joda-time lib. DateTime is immutable - and once created the values do not change, so class can safely be passed around and used in multiple threads without synchronization.
A companion mutable class to DateTime is MutableDateTime, of which the class can be modified and are not thread-safe.
DateTimeFormatter formatter = DateTimeFormat.forPattern("M/d/yyyy'T'HH:mm:ss.SSSZZ")
.withLocale(Locale.ROOT).withChronology(ISOChronology.getInstanceUTC());
DateTime dt = formatter.parseDateTime(text);
Reference of DateTimeFormatt: DatetimeFormat api.
As stated in ck1's answer, usage of java.time API is a better approach than the legacy classes. DateTimeFormatter is immutable and thread-safe, and using a static final instance of it will solve your problem.
The only part where I differ from that answer is in the code , where the Date class is used to get the time. I would like to take the java.time approach here as well. Below is my version :
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Instant.from(localDate.atStartOfDay(ZoneId.systemDefault())).toEpochMilli();
}
public static void main(String[] args) {
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
System.out.println(timestamp);
}
}

Creating a GregorianCalendar instance from milliseconds

I have a certain time in milliseconds (in a Timestamp object) and I want to use it to create a GregorianCalendar object. How can I do that?
EDIT: How do I do the reverse?
To get a GregorianCalendar object and not a Calendar object. Like Michael's answer provides, you can also do the following:
long timestamp = 1234567890;
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(timestamp);
This assumes a UTC epoch timestamp.
Just get an instance of GregorianCalendar and setTime with your java.sql.Timestamp timestamp:
Calendar cal=GregorianCalendar.getInstance();
cal.setTime(timestamp);
Edit:
As peterh pointed out, GregorianCalendar.getInstance() will not provide a GregorianCalendar by default, because it is inherited fromCalendar.getInstance(), which can provide for example a BuddhistCalendar on some installations. To be sure to use a GregorianCalender use new GregorianCalendar() instead.
Timestamp timestamp = new Timestamp(23423434);
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());
I believe this works, although it may not be the best approach:
import java.sql.Date;
import java.sql.Timestamp;
import java.util.GregorianCalendar;
public class TimestampToGregorianCalendar {
/**
* #param args
*/
public static void main(String[] args) {
Timestamp t = new Timestamp(12356342); // replace with existing timestamp
Date d = new Date(t.getTime());
Calendar gregorianCalendar = GregorianCalendar.getInstance();
gregorianCalendar.setTime(d);
}
}

Categories