Get name of day from timestamp in Android - java

I have a class that when its initialized, it records the time of initialization in a private field with a public getter:
public class TestClass {
private long mTimestamp;
public TestClass(){
mTimestamp = System.getCurrentMillis();
}
public long getTimestamp(){
return mTimestamp;
}
}
I also have an enum with the name of days:
public enum Days implements Serializable {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Now the problem is in another class I have to get the timestamp and set a Days field to the day that the class was initialized:
public class OtherClass {
public Days getDayOfInitialization(TestClass testClass){
//how to do this?
Date date = new Date(testClass.getTimestamp())
Days day = Date.getDay(); //Deprecated!
//convert to enum and return...
}
}
The getDay() method of Date is deprecated...how should I do this?

If you just need the current day of week in a human-readable format, formatted to the current user's locale, then you could use this:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String dayString = sdf.format(new Date());
If their locale is "en_US", the output is:
Wednesday
If their locale is "de_DE", the output is:
Mittwoch
If their locale is "fr_FR", the output is:
mercredi
But if you need a numerical representation of the day of week (for example, you wanted to get '1' if it is Sunday or '2' if it is Monday), then you could use Calendar:
Calendar cal = Calendar.getInstance();
int dayInt = cal.get(Calendar.DAY_OF_WEEK);

use Calendar:
long timeStamp = testClass.getTimestamp();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(timeStamp);
int dayNum = c.get(Calendar.DAY_OF_WEEK);
Days day = Days.values()[dayNum];
return day;

Standard Week
You do not need that Enum as the standard for date-time (ISO 8601) defines a week as Monday to Sunday.
Joda-Time defines constants for each day-of-week name in English such as DateTimeConstants.MONDAY.
Avoid java.util.Date
You should be using Joda-Time library, as the java.util.Date and .Calendar classes are notoriously troublesome. Joda-Time works in Android according to others.
Avoid Milliseconds As Date-Time
Tracking date-time as milliseconds is less than optimal. Serializing to a ISO 8601 string is preferable. But if you must, so be it.
Time Zone Is Crucial
Time zone is crucial. Day-of-week is defined by time zone, as the comments above discussed.
If you want UTC, Joda-Time provides the constant DateTimeZone.UTC.
Joda-Time
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( millisSinceEpochInUtc, timeZone );
int dayOfWeekNumber = dateTime.getDayOfWeek(); // ISO 8601 standard says Monday is 1.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEEE" ).withLocale( java.util.Locale.ENGLISH );
String dayOfWeekName = formatter.print( dateTime );

You should use Calendar.getInstance() method, which provide a calendar based on System Settings' TimeZone
Calendar now = Calendar.getInstance();
Then get the day of the week as an int (1 = Sunday, 2 = Monday, and so on...)
int day = now.get(Calendar.DAY_OF_WEEK);

Related

Simple date format day of week displays same day

I'm having issues with the below code displays Thursday as the dayOfTheWeek regardless of the date. Any ideas where I've gone wrong with this?
public void CreatePlan() {
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Integer plan_recipe = 0;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, date, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
… Any ideas where I've gone wrong with this?
day in your program is the day of the month from 1 to 31. Therefore d_name holds this number too.
Your SimpleDateFormat accepts formatting a number as a date and time expecting a count of milliseconds since the epoch of January 1, 1970 at 00:00 in UTC. So it will always format a date and time within the first 31 milliseconds after the epoch. Depending on your time zone the point in time that you format falls either on Wednesday, December 31, 1969 or on Thursday, January 1, 1970. So you will either always get Wednesday or always Thursday.
SimpleDateFormat.format(Object) accepts either a Date or a Number. Since Integer is a subclass of Number, it works as described.
The SimpleDateFormat class is notoriously troublesome, you have seen but a small corner of the problems that people often have with it. The Calendar class used in one other answer is poorly designed too. Both are long outdated. I suggest you look into java.time, the modern Java date and time API instead.
Further link: My answer to another question about getting the day of week from an Android date picker.
You are getting the value of the day-of-the-month, the month and the year in the following lines of code but you are not setting these values into the Calendar object which is supposed to give you other information (e.g. the day-of-week) by processing these values:
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
So, before you try to get any other information from the Calendar object, set these values to the object as shown below:
// Set the picked values into an instance of Calendar
Calendar calendar = Calendar.getInstance();
calendar.clear();// Make sure to call this to reset all fields
calendar.set(year, month - 1, day);// Make sure to decrease month by 1
Now, your rest of code will work as you are expecting e.g. let's say you select 4 as the day-of-the-month, 10 as the month, and 2020 as the year, the following code will give you Sunday as the day-of-the-week.
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
int day = 4;
int month = 10;
int year = 2020;
// Set the picked values into an instance of Calendar
Calendar calendar = Calendar.getInstance();
calendar.clear();// Make sure to call this to reset all fields
calendar.set(year, month - 1, day);// Make sure to decrease month by 1
System.out.println(calendar.getTime());
// Your desired format
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
// The day-of-the-week for the specified date
String dayOfTheWeek = sdf.format(calendar.getTime());
System.out.println(dayOfTheWeek);
}
}
Output:
Sun Oct 04 00:00:00 BST 2020
Sunday
Note that I have decreased the month (picked from the date-picker) by 1 because java.util date-time API is based on 0 as the month of January.
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (from the package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
If your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
By using the modern date-time API:
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int dayOfMonth = 4;
int month = 10;
int year = 2020;
// Instantiate a LocalDate object using the picked values
LocalDate date = LocalDate.of(year, month, dayOfMonth);
// The day-of-the-week for the specified date
String dayOfTheWeek = date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(dayOfTheWeek);
}
}
Output:
Sunday
You have to create Date from your datepicker, then format it to find day like below:
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
dayOfTheWeek = sdf.format(calendar.getTime());

How to replace getDate() from the type Date which is deprecated?

I have an existing program that I have to correct . It contains these lines :
Date startDate = new Date();
int day = startDate.getDate() - 1;
but getDate() from the type Date is deprecated so i have to change it using Calender. I tried this :
Calendar startDate = Calendar.getInstance();
startDate.add(Calendar.DATE, -1);
int day= startDate.getTime();
but this results into following error :
Type mismatch: cannot convert from Date to int
One more good option is to use like :
System.out.println(DateFormat.getDateInstance().format(new Date()));
It will print the current date.
If you need time along with date then you can use like :
System.out.println(DateFormat.getDateTimeInstance().format(new Date()));
If you want to get day in month use this:
int day= startDate.get(Calendar.DAY_OF_MONTH);
If you want to get day in week use this:
int day= startDate.get(Calendar.DAY_OF_WEEK);
Also be careful about day of week, because day 0 is sunday not monday.
Field number for get and set indicating the day of the week. This
field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY.
Type mismatch: cannot convert from Date to int
change
int day= startDate.getTime();
to
Date dat= startDate.getTime();//return type Date
As the javadocs suggest, use Calendar.get(Calendar.DAY_OF_MONTH)
To get the day of the month:
int day= startDate.get(Calendar.DAY_OF_MONTH);
From the Javadocs:
Field number for get and set indicating the day of the month. This is
a synonym for DATE. The first day of the month has value 1.
The getTime() function will return a Date Object which cannot be converted to int. If you want to get the day as an integer, you have to use:
int day = startDate.get(Calendar.DATE)
In Date#startDate.getDate() returns the day of the month :
Code#1-->
Date startDate = new Date();
int day = startDate.getDate() - 1;
System.out.println(day);
Through Calendar#.get(Calendar.DAY_OF_MONTH) you will get the same result as Date#startDate.getDate():
Code#2-->
Calendar startDate = Calendar.getInstance();
int day= startDate.get(Calendar.DAY_OF_MONTH)-1;
System.out.println(day);
So you can replace Code#1 by Code#2
See on java doc at http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime():
Date object of getTime() method return long not in int so use like:
long time = startDate.getTime();
For Calendar docs http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getTime()
Use like below:
long time = startDate.getTime().getTime();
For day of month:
Calendar c = Calendar.getInstance();
int dayOfMonth = c.get(Calendar.DATE);
java.time
The old java.util.Date/.Calendar classes are notoriously troublesome. They have been supplanted in Java 8 and later by the new java.time framework.
Note the use of time zone. Crucial in determining a date. If omitted, you implicitly rely on the JVM’s current default time zone. Better to specify the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
int dayOfMonth = now.getDayOfMonth();
int dayOfWeek = now.getDayOfWeek().getValue();
int dayOfYear = now.getDayOfYear();
Simply type int day = startDate.get(Calendar.DAY_OF_WEEK);

Set time to 00:00:00

I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.
This is my code :
/**
* Resets milliseconds, seconds, minutes and hours from the provided date
*
* #param date
* #return
*/
public static Date trim(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.
I know that 12:00:00 == 00:00:00!
I am using AppEngine. Is this an appengine bug, problem or some other issue? Or does it depend on something else?
Use another constant instead of Calendar.HOUR, use Calendar.HOUR_OF_DAY.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY uses 0-23.
To quote the Javadocs:
public static final int HOUR
Field number for get and set indicating
the hour of the morning or afternoon. HOUR is used for the 12-hour
clock (0 - 11). Noon and midnight are represented by 0, not by 12.
E.g., at 10:04:15.250 PM the HOUR is 10.
and
public static final int HOUR_OF_DAY
Field number for get and set
indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour
clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
Output:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
java.time
Using the java.time framework built into Java 8 and later. See Tutorial.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00
If you do not need time-of-day (hour, minute, second etc. parts) consider using LocalDate class.
LocalDate.now(); # 2015-11-19
Here are couple of utility functions I use to do just this.
/**
* sets all the time related fields to ZERO!
*
* #param date
*
* #return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* #param date
* #param hourOfDay
* #param minute
* #param second
* #param ms
*
* #return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}
One more JAVA 8 way:
LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
But it's a lot more useful to edit the date that already exists.
See the below code:
String datePattern24Hrs = "yyyy-MM-dd HH:mm:ss";
String datePattern12Hrs = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat simpleDateFormat24Hrs = new SimpleDateFormat(datePattern24Hrs);
SimpleDateFormat simpleDateFormat12Hrs = new SimpleDateFormat(datePattern12Hrs);
Date dateNow = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateNow);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dateTime = calendar.getTime();
String dateTimeIn24Hrs = simpleDateFormat24Hrs.format(dateTime);
String dateTimeIn12Hrs = simpleDateFormat12Hrs.format(dateTime);
System.out.println("DateTime in 24Hrs: ".concat(dateTimeIn24Hrs));
System.out.println("DateTime in 12Hrs: ".concat(dateTimeIn12Hrs));
The expected output is as below:
DateTime in 24Hrs: 2021-06-29 00:00:00
DateTime in 12Hrs: 2021-06-29 12:00:00
I hope it helps with the answer you are looking for.
You would better to primarily set time zone to the DateFormat component like this:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Then you can get "00:00:00" time by passing 0 milliseconds to formatter:
String time = dateFormat.format(0);
or you can create Date object:
Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);
or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);
dateFormat.format(calendar.getTime());
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant() // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate() // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date ➙ Instant
A java.util.Date represent a moment in UTC. Its replacement is Instant. Call the new conversion methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Time zone
Specify the time zone in which you want your new time-of-day to make sense.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime
Apply the ZoneId to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Changing time-of-day
You asked to change the time-of-day. Apply a LocalTime to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
First moment of day
But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.
LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
Adjust to UTC
If you need to go back to UTC, extract an Instant.
Instant instant = zdtFirstMomentOfDay.toInstant() ;
Instant ➙ Date
If you need a java.util.Date to interoperate with old code not yet updated to java.time, convert.
java.util.Date d = java.util.Date.from( instant ) ;
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
Another simple way,
final Calendar today = Calendar.getInstance();
today.setTime(new Date());
today.clear(Calendar.HOUR_OF_DAY);
today.clear(Calendar.HOUR);
today.clear(Calendar.MINUTE);
today.clear(Calendar.SECOND);
today.clear(Calendar.MILLISECOND);
Doing this could be easier (In Java 8)
LocalTime.ofNanoOfDay(0)
Before Java 8:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
After Java 8:
LocalDateTime.now().with(LocalTime.of(0, 0, 0))
Another way to do this would be to use a DateFormat without any seconds:
public static Date trim(Date date) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date trimmed = null;
try {
trimmed = format.parse(format.format(date));
} catch (ParseException e) {} // will never happen
return trimmed;
}
You can either do this with the following:
Calendar cal = Calendar.getInstance();
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date date = cal.getTime();
If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));
//Result is: Current Date: 29-10-2018 00:00:00

java get the current computer's date

how can i get computer's date on java, i want just year, month, day
i tried to get calender like this
Calendar c =Calendar.getInstance();
c.clear(Calendar.HOUR)
but can't know to deal with it,
First link on google:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date);
}
Try this ONE line of code.....
// Prints 01-07-2012
System.out.println(new SimpleDateFormat("dd-MM-YYYY").format(new Date()));
// Prints 01-Jul-2012
System.out.println(new SimpleDateFormat("dd-MMM-YYYY").format(new Date()));
Calendar rightNow = Calendar.getInstance();
int y = rightNow.get(Calendar.YEAR);
int m = rightNow.get(Calendar.MONTH) + 1;
int d = rightNow.get(Calendar.DAY_OF_MONTH);
System.out.println("year "+y+" month "+m+" day "+d);
You can obtain the current date as a year/month/day string like this:
String strDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
System.out.println(strDate);
> 2012-07-01
Notice that a Date object will always contain year, month, day, hours, minutes, seconds, milliseconds, etc., and by calling new Date() you obtain a date object with the current time.
If you only need some fields of a date (say, year, month and day) you need to format the date using a formatter, for instance SimpleDateFormat. Check the link for learning more about the string formatting options available in Java.
Joda-Time
Some example code using the Joda-Time 2.4 library.
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310).
Time Zone
Note the use of a time zone. A time zone is necessary to determine a date. The same simultaneous moment in Kolkata and Paris may have different dates on the calendar. If you omit a time zone, the JVM’s current default time zone will be applied. That means your results may vary, so best to explicitly specify the time zone you intend.
Example Code
String output = LocalDate.now( TimeZone.forID( "Asia/Kolkata" ) ).toString();

Java program to get the current date without timestamp

I need a Java program to get the current date without a timestamp:
Date d = new Date();
gives me date and timestamp.
But I need only the date, without a timestamp. I use this date to compare with another date object that does not have a timestamp.
On printing
System.out.println("Current Date : " + d)
of d it should print May 11 2010 - 00:00:00.
A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.
As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.
As explained into the Javadoc of java.util.Calendar.clear(int field):
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.
You could always use apache commons' DateUtils class. It has the static method isSameDay() which "Checks if two date objects are on the same day ignoring time."
static boolean isSameDay(Date date1, Date date2)
Use DateFormat to solve this problem:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormat2 = new SimpleDateFormat("MM-dd-yyyy");
print(dateFormat.format(new Date()); // will print like 2014-02-20
print(dateFormat2.format(new Date()); // will print like 02-20-2014
I did as follows and it worked: (Current date without timestamp)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
You can get by this date:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());
You could use
// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
Have a look at the Formatter API documentation.
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
java.time
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
Today
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
Moment
If you care about specific moments, specific points on the timeline, do not use LocalDate. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Strings
Call toString to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter class.
Joda-Time
Though now supplanted by java.time, you can use the similar LocalDate class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Also you can use apache commons lib DateUtils.truncate():
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
Time will be set to 00:00:00 so you can work with this date or print it formatted:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(now); // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated); // 2010-05-11 00:00:00
private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
private static Date NOW = new Date();
static {
try {
NOW = df1.parse(df1.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
}
I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.
Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();
Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates
Date compareToDate; // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
today.get( Calendar.DAY_OF_YEAR ) == compareTo.get( Calendar.DAY_OF_YEAR ) ) {
// They are the same day!
}
Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.
java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);
Thread.sleep(2000);
java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);
boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);
Output:
Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true
If you really want to use a Date instead for a Calendar for comparison, this is the shortest piece of code you could use:
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).getTime();
This way you make sure the hours/minute/second/millisecond values are blank.
I did as follows and it worked:
calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime(); // Convert it to date
Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)
I was looking for the same solution and the following worked for me.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date today = calendar.getTime();
Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and
the the resolution rule for the time of day is applied. Clearing one
of the fields doesn't reset the hour of day value of this Calendar.
Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
With the above posted solution I get output as
Wed Sep 11 00:00:00 EDT 2013
Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.
Here is my code for get only date:
Calendar c=Calendar.getInstance();
DateFormat dm = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
System.out.println("current date is : " + dm.format(date));
Here is full Example of it.But you have to cast Sting back to Date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
Date thisDate = new Date();//changeFormat.parse("10 07 2012");
System.out.println("Current Date : " + thisDate);
changeFormat.format(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(thisDate);
System.out.println(strDateOutput);
}
}

Categories

Resources