How do I get the date of 31 days ago? - java

How can I get x which should be 31 days before current_date?
x(date)___________________________current_date
31

Just subtract 31 days. For example:
LocalDate current = new LocalDate(2015, 6, 19);
LocalDate x = current.minusDays(31); // 2015-05-19
To get the current date, you could use:
LocalDate current = new LocalDate(); // Default time zone
or
LocalDate current = new LocalDate(zone); // Some specific zone
Or you may want to create your own "clock" representation which is able to give you the current Instant, in which case you'd use:
LocalDate current = clock.getCurrentInstant().toDateTime(zone).toLocalDate();
(That lets you use dependency injection to write simpler unit tests with a fake clock.)

You can try this:
LocalDate current = new LocalDate();//Constructs an instance set to the current local time evaluated using ISO chronology in the default zone.
LocalDate x = current.minusDays(31);
Or otherwise you can try:
LocalDate current = LocalDate.now();//Obtains a LocalDate set to the current system millisecond time using ISOChronology in the default time zone
LocalDate x = current.minusDays(31);

You can used JODA API if you want, its very advance and useful features:
String DATE_PATTERN = "dd/MM/yyyy";
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_PATTERN);
String systemDate = formatter.print(DateTime.now());
System.out.println("Current Date : " + systemDate);
String newDate = formatter.print(DateTime.now().minusDays(31));
System.out.println("Date 31 days ago : " + newDate);
Output:
Current Date : 19/06/2015
Date 31 days ago : 19/05/2015

Related

How to convert a String contains timestamp with offset

I have a String contains date and time like below :
String test = ""20220215160000Z-0400";
The correct value that I need to print out is :
Date = 02/15/2022
Time = 12:00
The time is basically the 16:00 - 4 hours in the offset. I couldn't figure out how to do it. Any helps will be appreciated. Currently, my codes is like below :
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
Date parsedDate = dateFormat.parse(test);
Timestamp timeStamp = new Timestamp(parsedDate.getTime());
System.out.println(timeStamp.toString());
And the print out is : 2022-02-15 16:00:00.0
I need the value to be 2022-02-15 12:00:00.0
using java.time api(you can change it to java easily):
var str = "20220215160000Z-0400"
var formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z")
var zonedDate = ZonedDateTime.parse(str, formatter)
println(zonedDate.offset)
var offsetTime = zonedDate.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.of("-0800"))
var for2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
println(for2.format(offsetTime))
notice i'm using ZoneOffset.of("-0800") instead of ZoneOffset.of("-0000")
Your date format is quite strange: as it does not reflect local time but UTC time, "20220215160000Z-0400" is normally regarded as local time (UTC-4) = 1600 HRS, but based on your explanation you'd like it such that UTC time = 1600 HRS, and therefore local time is 1200 HRS.
This means you need to have a "fix" on the date. See the sample code below:
String test = "20220215160000Z-0400";
ZoneId desiredZone = ZoneOffset.of("-0400");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss'Z'Z");
LocalDateTime localDateTime = LocalDateTime.parse(test, formatter);
ZonedDateTime min4HrsZonedDateTime = ZonedDateTime.of(localDateTime, desiredZone);
ZonedDateTime min4HrsZonedDateTimeFix = min4HrsZonedDateTime.withZoneSameLocal(ZoneOffset.UTC).withZoneSameInstant(desiredZone);
System.out.println("timestamp = " +Timestamp.from(min4HrsZonedDateTimeFix.withZoneSameLocal(ZoneOffset.systemDefault()).toInstant()));
I converted the time back to UTC but without using timezone, hence the min4HrsZonedDateTimeFix

Covert date time from one zone to another

This is continuation to one of my previous question where I am not able to parse the date which is resolved now. In the below code, I have a date string and I know the time zone for the date string even though the string itself doesn't contain it. Then I need to convert the date into EST time zone.
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
When I am running the code I am expecting ts1 to remain same and ts to be up by 1 hr. But iam getting below which I don't understand. I thought EST is one hour ahead of CST and so if it is 11 in CST, it should be 12 in EST. Also there seems to be offset by about eleven and half hours. Any clues on what I am missing.
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
I think the below code will help you.
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Copied from : http://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/
The method withZoneRetainFields() preserves the fields in the timezone CST (= UTC-06) hence your local timestamp (as LocalDateTime) but combines it with a different timezone (EST = UTC-05) which is one hour ahead in offset and result in a different instant. You should it interprete it this way: The same local time happens one hour earlier in New York compared to Chicago.
The rule is to subtract positive offsets and to add negative offsets in order to make timestamp representations of instants comparable (normalizing to UTC offset).
Alternatively: Maybe you don't want this but want to preserve the instant instead of the local fields. In this case you have to use the method withZone().
Side notice: Effectively, you compare the instants represented by the variables temp and date and finally use your default timezone to print these instants in the JDBC-escape-format (explanation - you implicitly use Timestamp.toString()). I would rather recommend to use a dedicated instant formatter for this purpose or simpler (to have the offsets in focus):
System.out.println(temp.toInstant() + " = " + date.toInstant());

java.util.Date and getYear()

I am having the following problem in Java (I see some people are having
a similar problem in JavaScript but I'm using Java)
System.out.println(new Date().getYear());
System.out.println(new GregorianCalendar().getTime().getYear());
System.out.println(this.sale.getSaleDate().getYear());
System.out.println(this.sale.getSaleDate().getMonth());
System.out.println(this.sale.getSaleDate().getDate());
returns
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 112
I/System.out( 4274): 1
I/System.out( 4274): 11
I don't understand the 112 bit which I thought would have been 2012.
What's going on? Is the
java.util.Date class unusable? I am storing this as a field in several
of my classes to store a date and time. What should I do?
In addition to all the comments, I thought I might add some code on how to use java.util.Date, java.util.Calendar and java.util.GregorianCalendar according to the javadoc.
//Initialize your Date however you like it.
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
//Add one to month {0 - 11}
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
According to javadocs:
#Deprecated
public int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Returns:
the year represented by this date, minus 1900.
See Also:
Calendar
So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.
Use date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(datetime);
SimpleDateFormat df = new SimpleDateFormat("yyyy");
year = df.format(date);
Don't use Date, use Calendar:
// Beware: months are zero-based and no out of range errors are reported
Calendar date = new GregorianCalendar(2012, 9, 5);
int year = date.get(Calendar.YEAR); // 2012
int month = date.get(Calendar.MONTH); // 9 - October!!!
int day = date.get(Calendar.DAY_OF_MONTH); // 5
It supports time as well:
Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17);
int hour = dateTime.get(Calendar.HOUR_OF_DAY); // 15
int minute = dateTime.get(Calendar.MINUTE); // 16
int second = dateTime.get(Calendar.SECOND); // 17
The java documentation suggests to make use of Calendar class instead of this deprecated way
Here is the sample code to set up the calendar object
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Here is the sample code to get the year, month, etc.
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH));
Calendar also has support for many other useful information like, TIME, DAY_OF_MONTH, etc. Here the documentation listing all of them
Please note that the month are 0 based. January is 0th month.
tl;dr
LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone.
.getYear() // Extract the year number from that date.
2018
java.time
Both the java.util.Date and java.util.Calendar classes are legacy, now supplanted by the java.time framework built into Java 8 and later.
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, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-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( "Africa/Tunis" ) ;
If you want only the date without time-of-day, use LocalDate. This class lacks time zone info but you can specify a time zone to determine the current date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );
You can get the various pieces of information with getYear, getMonth, and getDayOfMonth. You will actually get the year number with java.time!
int year = localDate.getYear();
2016
If you want a date-time instead of just a date, use ZonedDateTime class.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & Java 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Yup, this is in fact what's happening. See also the Javadoc:
Returns:
the year represented by this date, minus 1900.
The getYear method is deprecated for this reason. So, don't use it.
Note also that getMonth returns a number between 0 and 11. Therefore, this.sale.getSaleDate().getMonth() returns 1 for February, instead of 2. While java.util.Calendar doesn't add 1900 to all years, it does suffer from the off-by-one-month problem.
You're much better off using JodaTime.
Java 8 LocalDate class is another option to get the year from a java.util.Date,
int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear();
Another option is,
int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
There are may ways of getting day, month and year in java.
You may use any-
Date date1 = new Date();
String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1);
System.out.println("Formatted Date 1: " + mmddyyyy1);
Date date2 = new Date();
Calendar calendar1 = new GregorianCalendar();
calendar1.setTime(date2);
int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11}
int year1 = calendar1.get(Calendar.YEAR);
String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1);
System.out.println("Formatted Date 2: " + mmddyyyy2);
LocalDateTime ldt1 = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy3 = ldt1.format(format1);
System.out.println("Formatted Date 3: " + mmddyyyy3);
LocalDateTime ldt2 = LocalDateTime.now();
int day2 = ldt2.getDayOfMonth();
int mont2= ldt2.getMonthValue();
int year2= ldt2.getYear();
String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2);
System.out.println("Formatted Date 4: " + mmddyyyy4);
LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute
DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy");
String mmddyyyy5 = ldt3.format(format2);
System.out.println("Formatted Date 5: " + mmddyyyy5);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(new Date());
int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE
int month3= calendar2.get(Calendar.MONTH) + 1;
int year3 = calendar2.get(Calendar.YEAR);
String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3);
System.out.println("Formatted Date 6: " + mmddyyyy6);
Date date3 = new Date();
LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd
int day4 = ld1.getDayOfMonth();
int month4= ld1.getMonthValue();
int year4 = ld1.getYear();
String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4);
System.out.println("Formatted Date 7: " + mmddyyyy7);
Date date4 = new Date();
int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth();
int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue();
int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear();
String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5);
System.out.println("Formatted Date 8: " + mmddyyyy8);
Date date5 = new Date();
int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5));
int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5));
int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5));
String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6);
System.out.println("Formatted Date 9: " + mmddyyyy9);
Year.now()
There's an easier way to use the java.time library in Java 8+. The expression:
java.time.Year.now().getValue()
returns the current year as a four-digit int, using your default time zone. There are lots of options for different time ZoneIds, Calendars and Clocks, but I think this is what you will want most of the time. If you want the code to look cleaner (and don't need any other java.time.*.now() functions), put:
import static java.time.Year.now;
at the top of your file, and call:
now().getValue()
as needed.
This behavior is documented in the java.util.Date -class documentation:
Returns a value that is the result of subtracting 1900 from the year
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone.
It is also marked as deprecated. Use java.util.Calendar instead.
try{
int year = Integer.parseInt(new Date().toString().split("-")[0]);
}
catch(NumberFormatException e){
}
Much of Date is deprecated.

How to convert date time from one time zone to another time zone

The records are getting saved according to time zone of US but if I want to show the same record back to user it should convert the server date time with(US Time Zone) to user's date time with user's Time Zone
If you type in google "Java date change timezone" or "Javascript date change timezone". You will have one of your results:
In Java (source: http://www.coderanch.com/t/417443/java/java/Convert-Date-one-timezone-another )
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
// Prints the date in the CET timezone
System.out.println(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
// Prints the date in the IST timezone
System.out.println(formatter.format(date));
Javascript (source: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329 )
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
alert(calcTime('Bombay', '+5.5'));
java.time
The old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
Use modern classes: the java.time framework built into Java 8 and later. Find back-ports for earlier Java 6 & 7 and for Android.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Apply a time zone (ZoneId) to get a ZonedDateTime.
Never use the 3-4 letter zone abbreviations such as EST or IST. They are neither standardized nor unique(!). Use proper time zone names, built in a continent/region format such as Asia/Kolkata, Pacific/Auckland, America/Los_Angeles.
ZoneId zoneId_Montreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt_Montreal = ZonedDateTime.ofInstant( instant , zoneId_Montreal );
Apply a different time zone to generate another ZonedDateTime adjusted to that time zone. Call withZoneSameInstant.
ZoneId zoneId_Paris = ZoneId.of( "Europe/Paris" ); // Or "Asia/Kolkata", etc.
ZonedDateTime zdt_Paris = zdt_Montreal.withZoneSameInstant( zoneId_Paris );
If you want to go back to UTC, ask for an Instant.
Instant instant = zdt_Paris.toInstant();
TimeZone fromTimezone =TimeZone.getTimeZone(from);
TimeZone toTimezone=TimeZone.getTimeZone(to);
long fromOffset = fromTimezone.getOffset(calendar.getTimeInMillis());
long toOffset = toTimezone.getOffset(calendar.getTimeInMillis());
long convertedTime = calendar.getTimeInMillis() - (fromOffset - toOffset);
//Convert date from one zone to another
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
Code To Get Berlin Time and Convert it into UTC Time
Calendar sc = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
String strt = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
sf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
sc.set(sc.get(Calendar.YEAR),sc.get(Calendar.MONTH), sc.get(Calendar.DATE),sc.get(Calendar.HOUR) , sc.get(Calendar.MINUTE));
strt = sf.format(sc.getTime());
System.out.println("Start :"+strt);

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