Reputation: 2597
I need a date object for date 2014-02-11. I can't directly create it like this,
Date myDate = new Date(2014, 02, 11);
So I'm doing like follows,
Calendar myCalendar = new GregorianCalendar(2014, 2, 11);
Date myDate = myCalendar.getTime();
Is there any easy way to create date object in java?
Upvotes: 147
Views: 473402
Reputation: 338276
LocalDate.of( 2014 , 2 , 11 )
If you insist on using the terrible old java.util.Date
class, convert from the modern java.time classes.
java.util.Date // Terrible old legacy class, avoid using. Represents a moment in UTC.
.from( // New conversion method added to old classes for converting between legacy classes and modern classes.
LocalDate // Represents a date-only value, without time-of-day and without time zone.
.of( 2014 , 2 , 11 ) // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
.atStartOfDay( // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" ) // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`.
) // Returns a `ZonedDateTime`.
.toInstant() // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
) // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.
If you want "easy", you should be using the new java.time package in Java 8 rather than the notoriously troublesome java.util.Date & .Calendar classes bundled with Java.
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes.
A LocalDate
class is offered by java.time to represent a date-only value without any time-of-day or time zone. You do need a time zone to determine a date, as a new day dawns earlier in Paris than in Montréal for example. The ZoneId
class is for time zones.
ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );
Dump to console:
System.out.println ( "today: " + today + " in zone: " + zoneId );
today: 2015-11-26 in zone: Asia/Singapore
Or use a factory method to specify the year, month, day.
LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );
localDate: 2014-02-11
Or pass a month number 1-12 rather than a DayOfWeek
enum object.
LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );
A LocalDate
has no real meaning until you adjust it into a time zone. In java.time, we apply a time zone to generate a ZonedDateTime
object. That also means a time-of-day, but what time? Usually makes sense to go with first moment of the day. You might think that means the time 00:00:00.000
, but not always true because of Daylight Saving Time (DST) and perhaps other anomalies. Instead of assuming that time, we ask java.time to determine the first moment of the day by calling atStartOfDay
.
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 zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
zdt: 2014-02-11T00:00+08:00[Asia/Singapore]
For back-end work (business logic, database, data storage & exchange) we usually use UTC time zone. In java.time, the Instant
class represents a moment on the timeline in UTC. An Instant object can be extracted from a ZonedDateTime by calling toInstant
.
Instant instant = zdt.toInstant();
instant: 2014-02-10T16:00:00Z
You should avoid using java.util.Date
class entirely. But if you must interoperate with old code not yet updated for java.time, you can convert back-and-forth. Look to new conversion methods added to the old classes.
java.util.Date d = java.util.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
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. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda-Time library is now in maintenance mode, and advises migration to the java.time classes. I am leaving this section in place for history.
For one thing, Joda-Time uses sensible numbering so February is 2
not 1
. Another thing, a Joda-Time DateTime truly knows its assigned time zone unlike a java.util.Date which seems to have time zone but does not.
And don't forget the time zone. Otherwise you'll be getting the JVM’s default.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );
java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );
Dump to console…
System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );
When run…
dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT
If you need to convert to a java.util.Date for use with other classes…
java.util.Date date = dateTimeSingapore.toDate();
Upvotes: 77
Reputation: 40036
Gotcha: passing 2 as month may give you unexpected result: in Calendar API, month is zero-based. 2 actually means March.
I don't know what is an "easy" way that you are looking for as I feel that using Calendar is already easy enough.
Remember to use correct constants for month:
Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
Another way is to make use of DateFormat, which I usually have a util like this:
public static Date parseDate(String date) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(date);
} catch (ParseException e) {
return null;
}
}
so that I can simply write
Date myDate = parseDate("2014-02-14");
Yet another alternative I prefer: Don't use Java Date/Calendar anymore. Switch to JODA Time or Java Time (aka JSR310, available in JDK 8+). You can use LocalDate
to represent a date, which can be easily created by
LocalDate myDate =LocalDate.parse("2014-02-14");
// or
LocalDate myDate2 = new LocalDate(2014, 2, 14);
// or, in JDK 8+ Time
LocalDate myDate3 = LocalDate.of(2014, 2, 14);
Upvotes: 162
Reputation: 3108
Simplest ways:
Date date = Date.valueOf("2000-1-1");
LocalDate localdate = LocalDate.of(2000,1,1);
LocalDateTime localDateTime = LocalDateTime.of(2000,1,1,0,0);
Upvotes: 0
Reputation: 1384
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
//format as u want
try {
String dateStart = "June 14 2018 16:02:37";
cal.setTime(sdf.parse(dateStart));
//all done
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 1
Reputation: 975
From Java8:
import java.time.Instant;
import java.util.Date;
Date date = Date.from(Instant.parse("2000-01-01T00:00:00.000Z"))
Upvotes: 23
Reputation: 4579
I think the best way would be using a SimpleDateFormat
object.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2014-02-11";
Date dateObject = sdf.parse(dateString); // Handle the ParseException here
Upvotes: 22
Reputation: 141
import java.io.*;
import java.util.*;
import java.util.HashMap;
public class Solution
{
public static void main(String[] args)
{
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1,"SUNDAY");
hm.put(2,"MONDAY");
hm.put(3,"TUESDAY");
hm.put(4,"WEDNESDAY");
hm.put(5,"THURSDAY");
hm.put(6,"FRIDAY");
hm.put(7,"SATURDAY");
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
String format = year + "/" + month + "/" + day;
Date date = null;
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(format);
}
catch(Exception e){
}
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(hm.get(dayOfWeek));
}
}
Upvotes: -1
Reputation: 39
I think your date comes from php and is written to html (dom) or? I have a php-function to prep all dates and timestamps. This return a formation that is be needed.
$timeForJS = timeop($datetimeFromDatabase['payedon'], 'js', 'local'); // save 10/12/2016 09:20 on var
this format can be used on js to create new Date...
<html>
<span id="test" data-date="<?php echo $timeForJS; ?>"></span>
<script>var myDate = new Date( $('#test').attr('data-date') );</script>
</html>
What i will say is, make your a own function to wrap, that make your life easyr. You can us my func as sample but is included in my cms you can not 1 to 1 copy and paste :)
function timeop($utcTime, $for, $tz_output = 'system')
{
// echo "<br>Current time ( UTC ): ".$wwm->timeop('now', 'db', 'system');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'db', 'local');
// echo "<br>Current time (USER): ".$wwm->timeop('now', 'D d M Y H:i:s', 'local');
// echo "<br>Current time with user lang (USER): ".$wwm->timeop('now', 'datetimes', 'local');
// echo '<br><br>Calculator test is users timezone difference != 0! Tested with "2014-06-27 07:46:09"<br>';
// echo "<br>Old time (USER -> UTC): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'system');
// echo "<br>Old time (UTC -> USER): ".$wwm->timeop('2014-06-27 07:46:09', 'db', 'local');
/** -- */
// echo '<br><br>a Time from db if same with user time?<br>';
// echo "<br>db-time (2019-06-27 07:46:09) time left = ".$wwm->timeleft('2019-06-27 07:46:09', 'max');
// echo "<br>db-time (2014-06-27 07:46:09) time left = ".$wwm->timeleft('2014-06-27 07:46:09', 'max', 'txt');
/** -- */
// echo '<br><br>Calculator test with other formats<br>';
// echo "<br>2014/06/27 07:46:09: ".$wwm->ntimeop('2014/06/27 07:46:09', 'db', 'system');
switch($tz_output){
case 'system':
$tz = 'UTC';
break;
case 'local':
$tz = $_SESSION['wwm']['sett']['tz'];
break;
default:
$tz = $tz_output;
break;
}
$date = new DateTime($utcTime, new DateTimeZone($tz));
if( $tz != 'UTC' ) // Only time converted into different time zone
{
// now check at first the difference in seconds
$offset = $this->tz_offset($tz);
if( $offset != 0 ){
$calc = ( $offset >= 0 ) ? 'add' : 'sub';
// $calc = ( ($_SESSION['wwm']['sett']['tzdiff'] >= 0 AND $tz_output == 'user') OR ($_SESSION['wwm']['sett']['tzdiff'] <= 0 AND $tz_output == 'local') ) ? 'sub' : 'add';
$offset = ['math' => $calc, 'diff' => abs($offset)];
$date->$offset['math']( new DateInterval('PT'.$offset['diff'].'S') ); // php >= 5.3 use add() or sub()
}
}
// create a individual output
switch( $for ){
case 'js':
$format = 'm/d/Y H:i'; // Timepicker use only this format m/d/Y H:i without seconds // Sett automatical seconds default to 00
break;
case 'js:s':
$format = 'm/d/Y H:i:s'; // Timepicker use only this format m/d/Y H:i:s with Seconds
break;
case 'db':
$format = 'Y-m-d H:i:s'; // Database use only this format Y-m-d H:i:s
break;
case 'date':
case 'datetime':
case 'datetimes':
$format = wwmSystem::$languages[$_SESSION['wwm']['sett']['isolang']][$for.'_format']; // language spezific output
break;
default:
$format = $for;
break;
}
$output = $date->format( $format );
/** Replacement
*
* D = day short name
* l = day long name
* F = month long name
* M = month short name
*/
$output = str_replace([
$date->format('D'),
$date->format('l'),
$date->format('F'),
$date->format('M')
],[
$this->trans('date', $date->format('D')),
$this->trans('date', $date->format('l')),
$this->trans('date', $date->format('F')),
$this->trans('date', $date->format('M'))
], $output);
return $output; // $output->getTimestamp();
}
Upvotes: -6
Reputation: 338
Try this
Calendar cal = Calendar.getInstance();
Date todayDate = new Date();
cal.setTime(todayDate);
// Set time fields to zero
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
todayDate = cal.getTime();
Upvotes: 3