Java program to get the current date without timestamp - java

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);
}
}

Related

SimpleDate format is not converting time to IST

I am trying to get time (HH:MM) from below code in IST format but it still display UTC date, time.
Please help.
public static void main (String args[]) throws ParseException {
String date = "2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = timeZone.getID();
// Convert to System format from UTC
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);
}
java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your date and time work. Then your task becomes pretty simple. Rather than a formatter for your input format I want to define a formatter for your desired time format:
private static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofPattern("HH:mm zzz", Locale.ENGLISH);
Now the operation goes in these few lines:
String date = "2021-07-05T14:17:00.000Z";
String finalTime = Instant.parse(date)
.atZone(ZoneId.systemDefault())
.format(TIME_FORMATTER);
System.out.println(finalTime);
Output when I ran in Europe/Dublin time zone:
15:17 IST
Here IST is for Irish Summer Time. IST has several meanings, and I wasn’t sure which one you intended. Also many of the other popular time zone abbreviations are ambiguous. IST may also mean Israel Standard Time, but not here, since Israel uses Israel Daylight Time or IDT at this time of year. One other interpretation is India Standard Time used in India and Sri Lanka, So let’s try running the code in Asia/Kolkata time zone.
19:47 IST
I am exploiting the fact that your string is in ISO 8601 format, the format that the classes of java.time parse and also print as their default, that is, without any specified formatter.
What went wrong in your code?
Your bug is here:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
You must never hardcode Z as a literal in your format pattern, which is what you are doing when enclosing it in single quotes. The Z is a UTC offset and needs to be parsed as such so that Java knows that your date and time are in UTC (which is what Z means). When you hardcode the Z, SimpleDateFormat understands the date and time to be in the default time zone of the JVM. So when afterward you try to convert into that time zone, the time of day is not changed. You’re converting into the time zone you already had. It’s a no-op.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Time Zone Abbreviations – Worldwide List
You are parsing the date using your default TimeZone, not UTC.
You never called format1.setTimeZone before parsing. A DateFormat uses the default timezone unless you set it to something else.
Let’s look at each line of your code:
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
That is getting the default TimeZone. You don’t need a Calendar object for that; just call TimeZone.getDefault().
String timezoneID = timeZone.getID();
There is no reason to call that. You already have a TimeZone object. Converting it to a string ID and back to a TimeZone is a pointless round-trip operation. So, you should remove all uses of timezoneID.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
That is the problem. The DateFormat doesn’t treat the 'Z' as anything special; it’s just a literal character which the DateFormat knows not to parse.
You need to actually tell the DateFormat that it’s parsing a UTC time:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
TimeZone utc = TimeZone.getTimeZone(ZoneOffset.UTC);
format1.setTimeZone(utc);
Date actualDate = format1.parse(date);
Instead of cutting out pieces of a formatted string, make a new DateFormat that does exactly what you want:
DateFormat timeFormat = new SimpleDateFormat("HH:mm z");
String finalTime = timeFormat.format(actualDate);
Since a SimpleDateFormat always uses the default TimeZone when it is created, there is no need to call this format object’s setTimeZone method.
I should mention that the java.time and java.time.format packages are much better for working with dates and times:
String date = "2021-07-05T14:17:00.000Z";
Instant instant = Instant.parse(date);
ZonedDateTime utcDateTime = instant.atZone(ZoneOffset.UTC);
ZonedDateTime istDateTime =
utcDateTime.withZoneSameInstant(ZoneId.systemDefault());
String finalTime = String.format("%tR %<tZ", istDateTime);
// Or:
// String finalTime = istDateTime.toLocalTime() + " "
// + itsDateTime.getZone().getDisplayName(
// TextStyle.SHORT, Locale.getDefault());
format1.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
is what you need since the 3-letter zone names are really deprecated. Plus:
String timezoneValue = format1.getTimeZone().getDisplayName(false, TimeZone.SHORT);
The method Calendar.getInstance() gets a calendar using the default time zone and locale - UTC±00:00.
Use "IST" instead of timeZone.getID().
Exemple:
String date="2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = "IST"; // <<<<<
// Convert to System format from UTC
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);

SimpleDateFormat sets current day for parsed date

Is there any way to use the following simpleDateFormat:
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
and when invoking:
simpleDateFormat.parse("12:32:21 JST");
to return current date on the Date object?
For these example, it will return:
Thu Jan 01 05:32:21 EET 1970
and not:
<<today>> 05:32:21 EET <<currentYear>>
as I need.
No, SimpleDateFormat needs explicity the date in the input string. If you're using Java 8, you can go with a LocalDateTime:
LocalDateTime localDateTime = LocalDate.now().atTime(5, 32, 21);
If you want to include a time-zone, you can use ZonedDateTime.
Construct another SimpleDateFormat to print today's date:
String today = new SimpleDateFormat("yyyy/MM/dd").print(new Date());
(Be careful here: you might want to set the time zone on the SimpleDateFormat, as "today" is different in different time zones).
Update the date format to include year, month and day:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
And then prepend the date string with the date you want:
simpleDateFormat.parse(today + " " + "12:32:21 JST");
A better solution using flexible default values (today instead of 1970-01-01) would be in Java-8 with the new built-in date-time-library located in package java.time:
String input = "12:32:21 JST";
String pattern = "HH:mm:ss z";
LocalDate today = LocalDate.now(ZoneId.of("Asia/Tokyo"));
DateTimeFormatter dtf =
new DateTimeFormatterBuilder().parseDefaulting(ChronoField.YEAR, today.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue()).parseDefaulting(
ChronoField.DAY_OF_MONTH,
today.getDayOfMonth()
).appendPattern(pattern).toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(input, dtf);
System.out.println(zdt); // 2016-12-23T12:32:21+09:00[Asia/Tokyo]
However, I still see a small bug related to the fact that this code makes a hardwired assumption about the used zone BEFORE parsing the real zone so please handle with care. Keep in mind that the current date depends on the zone. But maybe you only need to handle a scenario where just the Japan time is used by users.
Hint: You can also parse in two steps. First step with any kind of fixed default date in order to get the zone information of the text to be parsed. And then you can use this zone information for suggested solution above. An awkward but safe procedure.
You can use this code if you want to change only the year and the day
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
Date date = simpleDateFormatHour.parse("12:32:21 JST");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DAY_OF_YEAR, Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
date = calendar.getTime();

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.

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();

How to get the current date/time in Java [duplicate]

This question already has answers here:
How to get the current date and time
(10 answers)
Closed 2 years ago.
What's the best way to get the current date/time in Java?
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone1.
If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.
Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.
new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. https://stackoverflow.com/questions/6280829.)
in Java 8, calling java.time.LocalDateTime.now() and java.time.ZonedDateTime.now() will give you representations2 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations.
With Java 8 and later, the standard java.time package is recommended. Joda time is now considered "obsolete", and the Joda maintainers are recommending that people migrate.3.
1 - System.currentTimeMillis() gives the "system" time. While it is normal practice for the system clock to be set to (nominal) UTC, there will be a difference (a delta) between the local UTC clock and true UTC. The size of the delta depends on how well (and how often) the system's clock is synced with UTC.
2 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
3 - Note: your Java 8 code won't break if you don't migrate, but the Joda codebase may eventually stop getting bug fixes and other patches. As of 2020-02, an official "end of life" for Joda has not been announced, and the Joda APIs have not been marked as Deprecated.
(Attention: only for use with Java versions <8. For Java 8+ check other replies.)
If you just need to output a time stamp in format YYYY.MM.DD-HH.MM.SS (very frequent case) then here's the way to do it:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
If you want the current date as String, try this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
tl;dr
Instant.now() // Capture the current moment in UTC, with a resolution of nanoseconds. Returns a `Instant` object.
… or …
ZonedDateTime.now( // Capture the current moment as seen in…
ZoneId.of( "America/Montreal" ) // … the wall-clock time used by the people of a particular region (a time zone).
) // Returns a `ZonedDateTime` object.
java.time
A few of the Answers mention that java.time classes are the modern replacement for the troublesome old legacy date-time classes bundled with the earliest versions of Java. Below is a bit more information.
Time zone
The other Answers fail to explain how a time zone is crucial in determining the current date and time. For any given moment, the date and the time vary around the globe by zone. For example, a few minutes after midnight is a new day in Paris France while still being “yesterday” in Montréal Québec.
Instant
Much of your business logic and data storage/exchange should be done in UTC, as a best practice.
To get the current moment in UTC with a resolution in nanoseconds, use Instant class. Conventional computer hardware clocks are limited in their accuracy, so the current moment may be captured in milliseconds or microseconds rather than nanoseconds.
Instant instant = Instant.now();
ZonedDateTime
You can adjust that Instant into other time zones. Apply a ZoneId object to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
We can skip the Instant and get the current ZonedDateTime directly.
ZonedDateTime zdt = ZonedDateTime.now( z );
Always pass that optional time zone argument. If omitted, your JVM’s current default time zone is applied. The default can change at any moment, even during runtime. Do not subject your app to an externality out of your control. Always specify the desired/expected time zone.
ZonedDateTime do_Not_Do_This = ZonedDateTime.now(); // BAD - Never rely implicitly on the current default time zone.
You can later extract an Instant from the ZonedDateTime.
Instant instant = zdt.toInstant();
Always use an Instant or ZonedDateTime rather than a LocalDateTime when you want an actual moment on the timeline. The Local… types purposely have no concept of time zone so they represent only a rough idea of a possible moment. To get an actual moment you must assign a time zone to transform the Local… types into a ZonedDateTime and thereby make it meaningful.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z ); // Always pass a time zone.
Strings
To generate a String representing the date-time value, simply call toString on the java.time classes for the standard ISO 8601 formats.
String output = myLocalDate.toString(); // 2016-09-23
… or …
String output = zdt.toString(); // 2016-09-23T12:34:56.789+03:00[America/Montreal]
The ZonedDateTime class extends the standard format by wisely appending the name of the time zone in square brackets.
For other formats, search Stack Overflow for many Questions and Answers on the DateTimeFormatter class.
Avoid LocalDateTime
Contrary to the comment on the Question by RamanSB, you should not use LocalDateTime class for the current date-time.
The LocalDateTime purposely lacks any time zone or offset-from-UTC information. So, this is not appropriate when you are tracking a specific moment on the timeline. Certainly not appropriate for capturing the current moment.
A LocalDateTime has only a date and a time-of-day such as "noon on 23rd of January 2020", but we have no idea if that is noon in Tokyo Japan or noon in Toledo Ohio US, two different moments many hours apart.
The “Local” wording is counter-intuitive. It means any locality rather than any one specific locality. For example Christmas this year starts at midnight on the 25th of December: 2017-12-25T00:00:00, to be represented as a LocalDateTime. But this means midnight at various points around the globe at different times. Midnight happens first in Kiribati, later in New Zealand, hours more later in India, and so on, with several more hours passing before Christmas begins in France when the kids in Canada are still awaiting that day. Each one of these Christmas-start points would be represented as a separate ZonedDateTime.
From outside your system
If you cannot trust your system clock, see Java: Get current Date and Time from Server not System clock and my Answer.
java.time.Clock
To harness an alternate supplier of the current moment, write a subclass of the abstract java.time.Clock class.
You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ).
Instant instant = Instant.now( yourClockGoesHere ) ;
For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed, offset, tick, and more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
In Java 8 it is:
LocalDateTime.now()
and in case you need time zone info:
ZonedDateTime.now()
and in case you want to print fancy formatted string:
System.out.println(ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME))
Just create a Date object...
import java.util.Date;
Date date = new Date();
// 2015/09/27 15:07:53
System.out.println( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 15:07:53
System.out.println( new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()) );
// 09/28/2015
System.out.println(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime()));
// 20150928_161823
System.out.println( new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) );
// Mon Sep 28 16:24:28 CEST 2015
System.out.println( Calendar.getInstance().getTime() );
// Mon Sep 28 16:24:51 CEST 2015
System.out.println( new Date(System.currentTimeMillis()) );
// Mon Sep 28
System.out.println( new Date().toString().substring(0, 10) );
// 2015-09-28
System.out.println( new java.sql.Date(System.currentTimeMillis()) );
// 14:32:26
Date d = new Date();
System.out.println( (d.getTime() / 1000 / 60 / 60) % 24 + ":" + (d.getTime() / 1000 / 60) % 60 + ":" + (d.getTime() / 1000) % 60 );
// 2015-09-28 17:12:35.584
System.out.println( new Timestamp(System.currentTimeMillis()) );
// Java 8
// 2015-09-28T16:16:23.308+02:00[Europe/Belgrade]
System.out.println( ZonedDateTime.now() );
// Mon, 28 Sep 2015 16:16:23 +0200
System.out.println( ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME) );
// 2015-09-28
System.out.println( LocalDate.now(ZoneId.of("Europe/Paris")) ); // rest zones id in ZoneId class
// 16
System.out.println( LocalTime.now().getHour() );
// 2015-09-28T16:16:23.315
System.out.println( LocalDateTime.now() );
Use:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp );
(It's working.)
There are many different methods:
System.currentTimeMillis()
Date
Calendar
Create object of date and simply print it down.
Date d = new Date(System.currentTimeMillis());
System.out.print(d);
java.util.Date date = new java.util.Date();
It's automatically populated with the time it's instantiated.
Similar to above solutions. But I always find myself looking for this chunk of code:
Date date=Calendar.getInstance().getTime();
System.out.println(date);
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43
For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
Reference: https://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
1st Understand the java.util.Date class
1.1 How to obtain current Date
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date = new Date(); // date object
System.out.println(date); // Try to print the date object
}
}
1.2 How to use getTime() method
import java.util.Date;
public class Main {
public static void main(String[]args){
Date date = new Date();
long timeInMilliSeconds = date.getTime();
System.out.println(timeInMilliSeconds);
}
}
This will return the number of milliseconds since January 1, 1970, 00:00:00 GMT for time comparison purposes.
1.3 How to format time using SimpleDateFormat class
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
class Demostration{
public static void main(String[]args){
Date date=new Date();
DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String formattedDate=dateFormat.format(date);
System.out.println(formattedDate);
}
}
Also try using different format patterns like "yyyy-MM-dd hh:mm:ss" and select desired pattern. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
2nd Understand the java.util.Calendar class
2.1 Using Calendar Class to obtain current time stamp
import java.util.Calendar;
class Demostration{
public static void main(String[]args){
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.getTime());
}
}
2.2 Try using setTime and other set methods for set calendar to different date.
Source: http://javau91.blogspot.com/
Have you looked at java.util.Date? It is exactly what you want.
Java 8 or above
LocalDateTime.now() and ZonedDateTime.now()
I find this to be the best way:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime())); // 2014/08/06 16:00:22
Have a look at the Date class. There's also the newer Calendar class which is the preferred method of doing many date / time operations (a lot of the methods on Date have been deprecated.)
If you just want the current date, then either create a new Date object or call Calendar.getInstance();.
As mentioned the basic Date() can do what you need in terms of getting the current time. In my recent experience working heavily with Java dates there are a lot of oddities with the built in classes (as well as deprecation of many of the Date class methods). One oddity that stood out to me was that months are 0 index based which from a technical standpoint makes sense, but in real terms can be very confusing.
If you are only concerned with the current date that should suffice - however if you intend to do a lot of manipulating/calculations with dates it could be very beneficial to use a third party library (so many exist because many Java developers have been unsatisfied with the built in functionality).
I second Stephen C's recommendation as I have found Joda-time to be very useful in simplifying my work with dates, it is also very well documented and you can find many useful examples throughout the web. I even ended up writing a static wrapper class (as DateUtils) which I use to consolidate and simplify all of my common date manipulation.
Use:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd::HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
The print statement will print the time when it is called and not when the SimpleDateFormat was created. So it can be called repeatedly without creating any new objects.
System.out.println( new SimpleDateFormat("yyyy:MM:dd - hh:mm:ss a").format(Calendar.getInstance().getTime()) );
//2018:02:10 - 05:04:20 PM
date/time with AM/PM
New Data-Time API is introduced with the dawn of Java 8. This is due
to following issues that were caused in the old data-time API.
Difficult to handle time zone : need to write lot of code to deal with
time zones.
Not Thread Safe : java.util.Date is not thread safe.
So have a look around with Java 8
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class DataTimeChecker {
public static void main(String args[]) {
DataTimeChecker dateTimeChecker = new DataTimeChecker();
dateTimeChecker.DateTime();
}
public void DateTime() {
// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("Date : " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month : " + month);
System.out.println("Day : " + day);
System.out.println("Seconds : " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(17).withYear(2018);
System.out.println("Date : " + date2);
//Prints 17 May 2018
LocalDate date3 = LocalDate.of(2018, Month.MAY, 17);
System.out.println("Date : " + date3);
//Prints 04 hour 45 minutes
LocalTime date4 = LocalTime.of(4, 45);
System.out.println("Date : " + date4);
// Convert to a String
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("Date : " + date5);
}
}
Output of the coding above :
Current DateTime: 2018-05-17T04:40:34.603
Date : 2018-05-17
Month : MAY
Day : 17
Seconds : 34
Date : 2018-05-17T04:40:34.603
Date : 2018-05-17
Date : 04:45
Date : 20:15:30
I created this methods, it works for me...
public String GetDay() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd")));
}
public String GetNameOfTheDay() {
return String.valueOf(LocalDateTime.now().getDayOfWeek());
}
public String GetMonth() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM")));
}
public String GetNameOfTheMonth() {
return String.valueOf(LocalDateTime.now().getMonth());
}
public String GetYear() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy")));
}
public boolean isLeapYear(long year) {
return Year.isLeap(year);
}
public String GetDate() {
return GetDay() + "/" + GetMonth() + "/" + GetYear();
}
public String Get12HHour() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("hh")));
}
public String Get24HHour() {
return String.valueOf(LocalDateTime.now().getHour());
}
public String GetMinutes() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("mm")));
}
public String GetSeconds() {
return String.valueOf(LocalDateTime.now().format(DateTimeFormatter.ofPattern("ss")));
}
public String Get24HTime() {
return Get24HHour() + ":" + GetMinutes();
}
public String Get24HFullTime() {
return Get24HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
public String Get12HTime() {
return Get12HHour() + ":" + GetMinutes();
}
public String Get12HFullTime() {
return Get12HHour() + ":" + GetMinutes() + ":" + GetSeconds();
}
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
you can use date for fet current data. so using SimpleDateFormat get format
just try this code:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CurrentTimeDateCalendar {
public static void getCurrentTimeUsingDate() {
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
DateFormat dateFormat = new SimpleDateFormat(strDateFormat);
String formattedDate= dateFormat.format(date);
System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate);
}
public static void getCurrentTimeUsingCalendar() {
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
System.out.println("Current time of the day using Calendar - 24 hour format: "+ formattedDate);
}
}
which the sample output is:
Current time of the day using Date - 12 hour format: 11:13:01 PM
Current time of the day using Calendar - 24 hour format: 23:13:01
more information on:
Getting Current Date Time in Java
Current Date using java 8:
First, let's use java.time.LocalDate to get the current system date:
LocalDate localDate = LocalDate.now();
To get the date in any other timezone we can use LocalDate.now(ZoneId):
LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30"));
We can also use java.time.LocalDateTime to get an instance of LocalDate:
LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
You can use Date object and format by yourself. It is hard to format and need more codes, as a example,
Date dateInstance = new Date();
int year = dateInstance.getYear()+1900;//Returns:the year represented by this date, minus 1900.
int date = dateInstance.getDate();
int month = dateInstance.getMonth();
int day = dateInstance.getDay();
int hours = dateInstance.getHours();
int min = dateInstance.getMinutes();
int sec = dateInstance.getSeconds();
String dayOfWeek = "";
switch(day){
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
}
System.out.println("Date: " + year +"-"+ month + "-" + date + " "+ dayOfWeek);
System.out.println("Time: " + hours +":"+ min + ":" + sec);
output:
Date: 2017-6-23 Sunday
Time: 14:6:20
As you can see this is the worst way you can do it and according to oracle documentation it is deprecated.
Oracle doc:
The class Date represents a specific instant in time, with millisecond
precision.
Prior to JDK 1.1, the class Date had two additional functions. It
allowed the interpretation of dates as year, month, day, hour, minute,
and second values. It also allowed the formatting and parsing of date
strings. Unfortunately, the API for these functions was not amenable
to internationalization. As of JDK 1.1, the Calendar class should be
used to convert between dates and time fields and the DateFormat class
should be used to format and parse date strings. The corresponding
methods in Date are deprecated.
So alternatively, you can use Calendar class,
Calendar.YEAR;
//and lot more
To get current time, you can use:
Calendar rightNow = Calendar.getInstance();
Doc:
Like other locale-sensitive classes, Calendar provides a class method,
getInstance, for getting a generally useful object of this type.
Calendar's getInstance method returns a Calendar object whose calendar
fields have been initialized with the current date and time
Below code for to get only date
Date rightNow = Calendar.getInstance().getTime();
System.out.println(rightNow);
Also, Calendar class have Subclasses. GregorianCalendar is a one of them and concrete subclass of Calendar and provides the standard calendar system used by most of the world.
Example using GregorianCalendar:
Calendar cal = new GregorianCalendar();
int hours = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int ap = cal.get(Calendar.AM_PM);
String amVSpm;
if(ap == 0){
amVSpm = "AM";
}else{
amVSpm = "PM";
}
String timer = hours + "-" + minute + "-" + second + " " +amVSpm;
System.out.println(timer);
You can use SimpleDateFormat, simple and quick way to format date:
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
Read this Jakob Jenkov tutorial: Java SimpleDateFormat.
As others mentioned, when we need to do manipulation from dates, we didn't had simple and best way or we couldn't satisfied built in classes, APIs.
As a example, When we need to get different between two dates, when we need to compare two dates(there is in-built method also for this) and many more. We had to use third party libraries. One of the good and popular one is Joda Time.
Also read:
How to get properly current date and time in Joda-Time?
JodaTime - how to get current time in UTC
Examples for JodaTime.
Download Joda
.
The happiest thing is now(in java 8), no one need to download and use libraries for any reasons. A simple example to get current date & time in Java 8,
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//with time zone
LocalTime localTimeWtZone = LocalTime.now(ZoneId.of("GMT+02:30"));
System.out.println(localTimeWtZone);
One of the good blog post to read about Java 8 date.
And keep remeber to find out more about Java date and time because there is lot more ways and/or useful ways that you can get/use.
Oracle tutorials for date & time.
Oracle tutorials for formatter.
Lesson: Standard Calendar.
EDIT:
According to #BasilBourque comment, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
I'll go ahead and throw this answer in because it is all I needed when I had the same question:
Date currentDate = new Date(System.currentTimeMillis());
currentDate is now your current date in a Java Date object.

Categories

Resources