Converting calendar to date in dd-MMM-yyyy format - java

I am trying to add 17 days to 10-APR-2014 and convert the date to dd-MMM-yyyy format, but I am getting Sun Apr 27 00:00:00 GMT+05:30 2014.
Here is my code:
import java.util.*;
import java.text.*;
public class HelloWorld{
public static void main(String []args){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 17);
String output = sdf.format(c.getTime());
System.out.println(output);
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").parse(output));
}
}
How can I make the output be 27-Apr-2014?

You are printing a Date parsed from a String formatted from the calendar date.
Instead, print the formatted calendar date:
System.out.print(new SimpleDateFormat("dd-MMM-yyyy").format(c.getTime()));
If displaying and using the dates is disjunct, do this:
Date date; // from Calendar or wherever
String str = new SimpleDateFormat("dd-MMM-yyyy").format(date));
// display str
Then when you want to do something with a selected date:
String selection;
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse(selection));
// do something with date

The answer by Bohemian is correct. Here I present an alternative solution.
Avoid j.u.Date
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Date-Only
If you need only a date, without any time component, both Joda-Time and java.time offer a LocalDate class.
Time Zone
Even for a date-only, you still need a time zone to get "today". At any moment the date may vary ±1 depending on your location on the globe. If you do not specify a time zone, the JVM's default time zone will be applied.
Example Code
Here is some example code in Joda-Time 2.3.
Determine "today" based on some time zone. Add seventeen days.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
LocalDate today = new LocalDate( timeZone );
LocalDate seventeenDaysLater = today.plusDays( 17 );
Generate a String representation of the date-time value…
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MMM-yyyy" );
String output = formatter.print( seventeenDaysLater );
Dump to console…
System.out.println( "today: " + today );
System.out.println( "seventeenDaysLater: " + seventeenDaysLater );
System.out.println( "output: " + output );
When run…
today: 2014-04-21
seventeenDaysLater: 2014-05-08
output: 08-May-2014

Related

Get only TimeZone field from new Date() in java

Requirement : I want to get only TimeZone field from new Date(), As of now from new Date() ,I am getting result as
Wed Jul 23 19:37:20 GMT+05:30 2014,But I want only GMT+05:30,Is there any way to get only this?
PS:I dont want to use split for getting timezone field.because this is my final option for achieving above requirement.
You should use the Calendar class and likely, the implementation GregorianCalendar. A lot of the Date functions have been deprecated in favor of using Calendar. Java 8 has the Clock API, but I'll assume Java 7 here.
That way you can do this:
Calendar calendar = new GregorianCalendar();
TimeZone tz = calendar.getTimeZone();
And work from there.
Assuming you have to work with a String input you can do something like this:
// format : dow mon dd hh:mm:ss zzz yyyy
String date = "Wed Jul 23 19:37:20 GMT+05:30 2014";
Pattern pattern = Pattern
.compile("^\\w{3}\\s\\w{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s?(.*)\\s\\d{4}$");
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
String timezone = matcher.group(1);
// beware : according to the Date.toString() documentation the timezone
// value can be empty
System.out.println(timezone);
} else {
System.out.println("doesn't match!");
}
import java.util package and use GregorianCalendar method.
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
Don't use Date and Time class of java.util package as their methods are deprecated means they may not be supported in future versions of JDK.
Generate String With Offset But No Date and No Time
Your question is inaccurate. A java.util.Date has no time zone (assumes to always be in UTC). The JVM's time zone is applied in the object' toString method and in other formatting code that generates a String representation. Therein lies your solution: use a date-time formatter that generates a String containing only the offset from UTC without the date or the time-of-day portions.
Avoid java.util.Date & .Calendar
Avoid using the bundled java.util.Date and .Calendar classes as they are notoriously troublesome. Instead use either Joda-Time or the new java.time package. Both support time zones as part of a date-time object.
Joda-Time
Here is how to generate a String representation of a DateTime in Joda-Time 2.3.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ZZ" );
String offset = formatter.print( dateTime ); // generates: +05:30
In Joda-Time 2.3 you can ask a DateTime object for its assigned time zone as an object. You may then interrogate the DateTimeZone object.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeZone timeZone = dateTime.getZone();
String id = timeZone.getID();

converting UTC date string to local date string inspecific format

I have a UTC date in string
String utcDate = "2014-03-05 07:09:07.0";
I want to convert it to local date string of format DD-MMM-YYYY hh:mm a
eg: 5-Mar-2014 12:39 PM from UTC date 2014-03-05 07:09:07.0
How this can be achieved using simple java or joda API
Very easy to achieve with default functionality. I hope the local data is for display only.
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = parser.parse(utcDate);
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM-yyyy hh:mm a");
System.out.println(formatter.format(parsed));
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
If you use the ISO 8601 format of strings, you can pass the string directly to a Joda-Time DateTime constructor. Your input string is close, but the space in the middle should be a T.
Some example code using the Joda-Time 2.3 library.
String input = "2014-03-05 07:09:07.0";
String inputModified = input.replace( " ", "T" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeUtc = new DateTime( inputModified, DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeUTC.toZone( timeZone );
String outputFrance = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( dateTimeParis );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-MMM-yyyy hh:mm a" ).withLocale( Locale.US );
String outputParisCustom = formatter.print( dateTimeParis );
Below code will help you to convert your UTC to IST or any other timezone. You need to pay attention to the timezone that you want to use with SimpleDateFormat.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class ConvertTimeZone {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-03-05 07:09:07");
System.out.println("time in UTC " +sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Time in IST is " + sdf.format(date));
}
}

issue with date/timezone in Java

I need to display time zone in CET in my java application.
And I am using following code to achieve this.
String OLD_FORMAT = "yyyyMMdd HH:mm:ss";
String NEW_FORMAT = "dd.MM.yyyy HH:mm:ss";
String date = "20140217 14:45:28";
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
TimeZone zone = TimeZone.getTimeZone("GMT+1");
sdf.setTimeZone(zone);
Date d = null;
d = sdf.parse(date);
sdf.applyPattern(NEW_FORMAT);
date = sdf.format(d);
and I am using the date object to print the date on UI.
OR
TimeZone zone = TimeZone.getTimeZone("CET");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
sdf.setTimeZone(zone);
But using the either of above piece of code i am getting GMT time which is one hour behind CET.
FOr example if I execute the code now, I will get 1:32:50 PM where as its 2:32:50 PM as per http://wwp.greenwichmeantime.com/time-zone/europe/european-union/central-european-time/
Any one any idea what might be going wrong here ?
UPDATE : I have found the issue. I made a silly mistake as I had to set the time first to GMT (the datetime i was getting was in GMT) and then change it to CET. Its working now. Thanks much everyone for the reply.
Maybe you are passing the wrong date to the SimpleDateFormat instance. I've written a small to test your code and it seems to work:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) {
TimeZone zone = TimeZone.getTimeZone("GMT+1");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
sdf.setTimeZone(zone);
TimeZone zone2 = TimeZone.getTimeZone("CET");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
sdf2.setTimeZone(zone2);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 15);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.setTimeZone(TimeZone.getTimeZone("GMT+3"));
System.out.println(sdf.format(c.getTime()));
System.out.println(sdf2.format(c.getTime()));
}
}
java.util.Date does not have a TimeZone, it's essentially a long (milliseconds since epoch). If you want to keep the timezone, you must use java.util.Calendar or even better, use joda-time
The second piece of code should do the trick.
Note that CET in java actually means CET in winter and CEST in summer which is what you want I assume. GMT+1 would not actually switch to summer time so you'd be stuck in winter time if you use that.
If the outputted value is still wrong you are giving it the wrong date to format.
Perhaps you made the same timezone error when parsing the date?
Avoid 3-Letter Codes
Those three-letter time zone codes are neither standardized nor unique. And they get confusing with regards to Daylight Saving Time (DST). Instead use proper time zone names.
There are a few dozen such names for +01:00. Choose the one that represents your applicable rules for DST and other anomalies. My example code arbitrarily chose Paris time zone.
Confusing Question
I could not understand if your input string represented a date-time at UTC or already in a +01:00 time zone. My example code below has two variations, covering both cases.
Also, you would have found your question already asked and answered many times on StackOverflow if you searched.
Joda-Time
The bundled java.util.Date and Calendar classes are notoriously troublesome. Avoid them. Use either:
Joda-Time
java.time.* package, new in Java 8(informed by Joda-Time, defined by JSR 310, and supplanting the old Date/Calendar classes)
Example Code
String input = "20140217 14:45:28";
// Formatters
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "yyyyMMdd HH:mm:ss" );
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "dd.MM.yyyy HH:mm:ss" );
// Use a proper time zone name rather than 3-letter codes.
DateTimeZone timeZoneParis = DateTimeZone.forID( "Europe/Paris" );
// If that input was meant to be in UTC, and then adjusted to +01:00.
DateTime dateTimeAsUtc = formatterInput.withZone( DateTimeZone.UTC ).parseDateTime( input );
DateTime dateTimeAdjustedToParis = dateTimeAsUtc.withZone( timeZoneParis );
// Or, if that input was already in +01:00.
DateTime dateTimeAsParis = formatterInput.withZone( timeZoneParis ).parseDateTime( input );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeAsUtc: " + dateTimeAsUtc );
System.out.println( "dateTimeAdjustedToParis: " + dateTimeAdjustedToParis );
System.out.println( "dateTimeAdjustedToParis thru formatter: " + formatterOutput.print( dateTimeAdjustedToParis ) );
System.out.println( "dateTimeAsParis: " + dateTimeAsParis );
When run…
input: 20140217 14:45:28
dateTimeAsUtc: 2014-02-17T14:45:28.000Z
dateTimeAdjustedToParis: 2014-02-17T15:45:28.000+01:00
dateTimeAdjustedToParis thru formatter: 17.02.2014 15:45:28
dateTimeAsParis: 2014-02-17T14:45:28.000+01:00
I use the following code to get the date and time of my country;
String TIME_SERVER = "time-a.nist.gov";
NTPUDPClient timeClient = new NTPUDPClient();
InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
Date time = new Date(returnTime);
Maybe it helps you, if it doesn't, just put a comment and i will delete my answer.

IST to EST Time Conversion In Java

I have a Date field in Java in IST Time. I want to convert the same to EST Time and the output should be as a Date Type only. I am able to accomplish the same using the below piece of code:-
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date date = new Date();
DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String estTime = timeFormat.format(date);
date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(estTime);
The problem with the above piece of code is that though the date is converted in EST Time, the Time Zone is still showing as IST and not EST. The rest of the date is converted perfectly fine. Is there any way to explicitly set the time Zone To EST in the Date Field.Any help regarding this will be highly appreciated.
-Subhadeep
The Date class is time-zone agnostic. Basically, it is always based on GMT although when it is printed it uses the current system time zone to adjust it.
However, Calendar is time-zone specific. See Calendar.setTimeZone().
Consider:
Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("America/New_York"));
cal.setTime(new Date());
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using java.time, the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
ZonedDateTime zdtIndia = instant.atZone(ZoneId.of("Asia/Calcutta"));
ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
System.out.println(zdtIndia);
System.out.println(zdtNewYork);
}
}
Output:
2021-05-19T21:08:54.241341Z
2021-05-20T02:38:54.241341+05:30[Asia/Calcutta]
2021-05-19T17:08:54.241341-04:00[America/New_York]
Instant represents an instantaneous point on the timeline. The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Learn more about java.time, the modern date-time API* from Trail: Date Time.
Solution using legacy API:
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.
Demo:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS[zzzzz]");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
String dtIndia = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String dtNewYork = sdf.format(date);
System.out.println(dtIndia);
System.out.println(dtNewYork);
}
}
Output:
Wed May 19 22:16:08 BST 2021
2021-05-20T02:46:08.024[India Standard Time]
2021-05-19T17:16:08.024[Eastern Daylight Time]
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and 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.
Should you add z for time-zone pattern in your SimpleDateFormat pattern?
So, it should be DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"). I changed your code like this:
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
dateTimeFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
Date date = new Date();
System.out.println(dateTimeFormat.format(date)); // this print IST Timezone
DateFormat timeFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
timeFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String estTime = timeFormat.format(date);
date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z", Locale.ENGLISH).parse(estTime);
System.out.println(timeFormat.format(date)); // this print EDT Timezone currently (on March)
}
In last print statement, current date format is printed with EDT Timezone (Eastern Daylight Time). Maybe because of this.
The correct answer by John B explains that java.util.Date seems to have a time zone but does not. Its toString method applies your JVM's default time zone when generating the string representation.
That is one of many reasons to avoid java.util.Date and .Calendar classes bundled with Java. Avoid them. Instead use either Joda-Time or the java.time package built into Java 8 (inspired by Joda-Time, defined by JSR 310).
Here is some example code in Joda-Time 2.3.
String input = "01/02/2014 12:34:56";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" );
DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = formatterInput.withZone( timeZoneIndia ).parseDateTime( input );
DateTimeZone timeZoneNewYork = DateTimeZone.forID( "America/New_York" );
DateTime dateTimeNewYork = dateTimeIndia.withZone( timeZoneNewYork );
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeNewYork: " + dateTimeNewYork );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 01/02/2014 12:34:56
dateTimeIndia: 2014-01-02T12:34:56.000+05:30
dateTimeNewYork: 2014-01-02T02:04:56.000-05:00
dateTimeUtc: 2014-01-02T07:04:56.000Z

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