1

I am wondering whats the proper way of creating Dates in Java? It appears the simnplest way

new Date(year, month, day, hours, mins) 

Is depreciated. So how should I create Dates. I understand the recommended way is to use long but whats an easy way to get the long value of a human readable date like "2012-03-21 2:00PM" (or something similar)?

5 Answers 5

6

Since Java 8 you can use the Calendar.Builder class:

Date date = new Calendar.Builder()
    .setDate(2012, 2, 21)
    .setTimeOfDay(14, 0, 0)
    .build().getTime();
Sign up to request clarification or add additional context in comments.

Comments

3

Use the Calendar class. Or Joda Time, as I'm sure someone else will suggest.

Calendar c = Calendar.getInstance();
c.set(year, month, day, hours, mins);
long time = c.getTimeInMillis();

2 Comments

@ErnestFriedman-Hill The OP is interested in the UTC value, not the Date, per se.
+1 for recommending Joda Time - Java's Date implementation is easily the worst out of any programming languages I've come across - it's cumbersome and unintuitive. Joda Time makes it much easier.
1

Example:

try { 
   String str_date="2012-03-21 2:00PM";
   DateFormat formatter ; 
   Date date ; 
   formatter = new SimpleDateFormat("yyyy-MMM-dd ha");
   date = (Date)formatter.parse(str_date);  
   Calendar cal=Calendar.getInstance();
   cal.setTime(date);
   System.out.println("Date to long " + cal.getTimeInMillis());
} catch (ParseException e)  {
  System.out.println("Exception :"+e);  
}  

Comments

0

You're supposed to build an appropriate Calendar -- which you can use by itself in many cases -- and just call getDate() on it if you really need a Date object.

Comments

0

You can use the GregorianCalendar for dates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.