java create date object using a value string
.Additional thing is if you want to convert a Date to String then you should use SimpleDateFormat#format function.
Now the Point for you is new Date(String) is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use SimpleDateFormat#parse .
refer the official doc for more Date and Time Patterns used in SimpleDateFormat options.
It is your date in String format.You need to set format in in new SimpleDateFormat(format) exactly as your string have and then just need to parse it.As your new java.text.SimpleDateFormat(«EEEE, dd/MM/yyyy/hh:mm:ss») .format(cald.getTime()) will return a String and in question I guess you want to convert it into Date then this is the way that I answered
the resutls for ur code is Thu Apr 25 00:23:26 PDT 2013 and it is not in the format which i want , why please?
Use SimpleDateFormat parse method:
import java.text.DateFormat; import java.text.SimpleDateFormat; String inputString = "11-11-2012"; DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; String inputString = "11-11-2012"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); LocalDate inputDate = LocalDate.parse(inputString,formatter);
Last line is missing the fromatter: It could be a follows LocalDate inputDate = LocalDate.parse(inputString, formatter);
import java.util.Date; import java.text.SimpleDateFormat;
Above is the import method, below is the simple code for Date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); system.out.println((dateFormat.format(date)));
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by «Java Bean»-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT—
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
Convert String to java.util.Date
When I retrieve the date with that format I am get every thing fine except the hour. The hour is always 00 . Here is my output:
String date--->29-Apr-2010,13:00:14 PM After convrting Date--->1272479414000--Thu Apr 29 00:00:14 GMT+05:30 2010
Date lScheduledDate = CalendarObj.getTime(); DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); SomeClassObj.setTime(formatter.format(lScheduledDate)); String lNextDate = SomeClassObj.getTime(); DateFormat lFormatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date lNextDate = (Date)lFormatter.parse(lNextDate); System.out.println("output here"+lNextDate);
Okay buddies Problem solved, problem with the AM/PM «letter aaa» in format, as I am using ‘HH’, ‘aaa’ should not be used, if you use ‘aaa’ then specify ‘hh’
While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar ), for anyone popping by in 2017 or later, those classes are now long outdated. Today one would use the classes in the java.time package, for example LocalDateTime and DateTimeFormatter . There are numerous answers on Stack Overflow to show you how. Go search.
4 Answers 4
I think your date format does not make sense. There is no 13:00 PM. Remove the «aaa» at the end of your format or turn the HH into hh.
Nevertheless, this works fine for me:
String testDate = "29-Apr-2010,13:00:14 PM"; DateFormat formatter = new SimpleDateFormat("d-MMM-yyyy,HH:mm:ss aaa"); Date date = formatter.parse(testDate); System.out.println(date);
It prints «Thu Apr 29 13:00:14 CEST 2010».
You declare your date format and then call the parse method with your string.
private static final DateFormat DF = new SimpleDateFormat(. ); Date myDate = DF.parse("1234");
And as Guillaume says, set the timezone!
Not related but DateFormat objects are not thread safe, they should not be declared static because it makes it more likely that they will be accessed from different threads at some point.
You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).
Your date string doesn’t have time zone info so the z letter won’t help, use setTimeZone(. ) on the SimpleDateFormat object instead
java.time
While in 2010, java.util.Date was the class we all used (toghether with DateFormat and Calendar ), those classes were always poorly designed and are now long outdated. Today one would use java.time, the modern Java date and time API.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy,HH:mm:ss"); String dateTimeStringFromSqlite = "29-Apr-2010,13:00:14"; LocalDateTime dateTime = LocalDateTime.parse(dateTimeStringFromSqlite, formatter); System.out.println("output here: " + dateTime);
What went wrong in your code?
The combination of uppercase HH and aaa in your format pattern strings does not make much sense since HH is for hour of day, rendering the AM/PM marker from aaa superfluous. It should not do any harm, though, and I have been unable to reproduce the exact results you reported. In any case, your comment is to the point no matter if one uses the old-fashioned SimpleDateFormat or the modern DateTimeFormatter :
‘aaa’ should not be used, if you use ‘aaa’ then specify ‘hh’
Lowercase hh is for hour within AM or PM, from 01 through 12, so would require an AM/PM marker.
- In your database, since I understand that SQLite hasn’t got a built-in datetime type, use the standard ISO 8601 format and store time in UTC, for example 2010-04-29T07:30:14Z (the modern Instant class parses and formats such strings as its default, that is, without any explicit formatter).
- Don’t use an offset such as GMT+05:30 for time zone. Prefer a real time zone, for example Asia/Colombo, Asia/Kolkata or America/New_York.
- If you wanted to use the outdated DateFormat , its parse method returns a Date , so you don’t need the cast in Date lNextDate = (Date)lFormatter.parse(lNextDate); .
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
- Oracle tutorial: Date Time explaining how to use java.time .
- Java Specification Request (JSR) 310, where java.time was first described.
- ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
- Wikipedia article: ISO 8601
How to get the current date/time in Java [duplicate]
@RamanSB LocalDateTime is not appropriate, as it purposely loses time zone information. You are discarding valuable information while gaining nothing in return. ZonedDateTime.now() retains time zone info. See my Answer for details.
Duplicate of Equivalent of C#’s DateTime.Now in Java? as was previously correctly marked. Also primarily opinion-based.
28 Answers 28
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-zone 1 .
- 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 representations 2 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.