Parsing String to Calendar in Java? - java

I am having trouble parsing a string to a calendar object in java by pulling it from an XML element (I'm writing an android app) so I can calculate the length of time between the time in the string and the current time. I am brand new to java and come from the .NET world, so any additional background here can be really helpful.
The code I am trying to use is:
// Using this class to define the format for date parsing.
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd HH:mm:ss", Locale.ENGLISH);
// readArrivalValue reads the element from XML, which seems to be working.
String prdt = readArrivalValue(parser, "prdt");
// At this point prdt evaluates to the correct value: "20150331 20:14:40"
Date datePRDT = sdf.parse(prdt);
// datePRDT doesn't seem to be set properly. It evaluates to:
// datePRDT = {java.util.Date#830031077456}"Sat Jan 31 20:14:40 CST 2015"
// milliseconds = 1422761216000
// element.prdt is of type Calendar. Nothing is done to this prior to this statement.
element.prdt.setTime(datePRDT); // This throws a null pointer exception

Two issues with your code:
Fix your SimpleDateFormat pattern as you're parsing minutes mm in place of months MM too!
new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.ENGLISH);
^
You most likely forgot to initialize your Calendar instance and hence get an NPE.
element.prdt = Calendar.getInstance();
element.prdt.setTime(datePRDT);

Related

java create date object using a value string

I am using this to get the current time :
java.util.Calendar cal = java.util.Calendar.getInstance();
System.out.println(new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime()));
I want to put the value (which I print it) into a date object, I tried this:
Date currentDate = new Date(value);
but eclipse tells me that this function is not good.
Edit
the value is the value that I printed to you using system.out.println
Whenever you want to convert a String to Date object then use SimpleDateFormat#parse
Try to use
String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);
.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.
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);
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.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
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.
converting a date string into milliseconds in java
Try this :-
try{
String valuee="25/04/2013";
Date currentDate =new SimpleDateFormat("dd/MM/yyyy").parse(valuee);
System.out.println("Date is ::"+currentDate);
}catch(Exception e){
System.out.println("Error::"+e);
e.printStackTrace();
}
Output:-
Date is ::Thu Apr 25 00:00:00 GMT+05:30 2013
Your value should be proper format.
In your question also you have asked for this below :-
Date currentDate = new Date(value);
This style of date constructor is already deprecated.So, its no more use.Being we know that Date has 6 constructor.Read more
Here is the optimized solution to do it with SimpleDateFormat parse() method.
SimpleDateFormat formatter = new SimpleDateFormat(
"EEEE, dd/MM/yyyy/hh:mm:ss");
String strDate = formatter.format(new Date());
try {
Date pDate = formatter.parse(strDate);
} catch (ParseException e) { // note: parse method can throw ParseException
e.printStackTrace();
}
Few things to notice
We don't need to create a Calendar instance to get the current date
& time instead use new Date()
Also it doesn't require 2 instances of SimpleDateFormat as
found in the most voted answer for this question. It's just a
waste of memory
Furthermore, catching a generic exception like Exception is a bad practice when we know that the parse method only stands a chance to throw a ParseException. We need to be as specific as possible when dealing with Exceptions. You can refer, throws Exception bad practice?
try this, it worked for me.
String inputString = "01-01-1900";
Date inputDate= null;
try {
inputDate = new SimpleDateFormat("dd-MM-yyyy").parse(inputString);
} catch (ParseException e) {
e.printStackTrace();
}
dp.getDatePicker().setMinDate(inputDate.getTime());
It is because value coming String (Java Date object constructor for getting string is deprecated)
and Date(String) is deprecated.
Have a look at jodatime or you could put #SuppressWarnings({“deprecation”}) outside the method calling the Date(String) constructor.
What you're basically trying to do is this:-
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
The reason being, the String which you're printing is just a String representation of the Date in your required format. If you try to convert it to date, you'll eventually end up doing what I've mentioned above.
Formatting Date(cal.getTime()) to a String and trying to get back a Date from it - makes no sense. Date has no format as such. You can only get a String representation of that using the SDF.

How to get particular parts of a DateTime object?

I have a DateTime object DT which stores current time. When I print DT, I want it to only print the time part, ie HH-MM-SS (H = hours, M = minutes, S = seconds) and ignore the date part.
How can I do this ? For that matter, is it even possible to create a date time object which will only contain HH-MM-SS and nothing related to date ? If that is true, then I can simply print it instead of extracting the HH-MM-SS part.
Thanks.
If you only want the time, you should use a LocalTime instead of a DateTime. You can use DateTime.toLocalTime() to get the time part of an existing DateTime.
If you actually want to keep the DateTime but only reveal the time part when formatting, you can create a DateTimeFormatter with a pattern which only includes the time parts, but I'd usually consider this a design smell.
You can use Java date formatter which is in java.util.Date package.
Like :
Date todaysDate = new java.util.Date();
1. // Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
2. // Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
3. // Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
With Java you can do it like this
Date obj = new Date() ;
System.out.println(new SimpleDateFormat("hh:mm:ss").format(obj)) ;
but it could be an expensive call.
But jodatime gives LocalTime which you can try out.

How can I get Date in MM/DD/YY format from Timestamp

I want to get the Date in MM/DD/YY format from a timestamp.
I have used the below method but it does not gives proper output
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(1306249409));
Log.d("Date--",""+cal.DAY_OF_MONTH);
Log.d("Month--",""+cal.MONTH);
Log.d("Year--",""+cal.YEAR);
But its gives the output like below
Date--5
Month--2
Year--1
The correct date is 24 May 2010 for Timestamp - 1306249409
Note - Timestamp is received by a webservice which is used in my application.
Better Approach
Simply Use SimpleDateFormat
new SimpleDateFormat("MM/dd/yyyy").format(new Date(timeStampMillisInLong));
Mistake in your Approach
DAY_OF_MONTH ,MONTH, .. etc are just constant int value used by Calendar class
internally
You can get the date represented by cal by cal.get(Calendar.DATE)
Use the SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String time = sdf.format(date);
What's wrong:
Calendar.DAY_OF_MONTH, Calendar.MONTH etc are static constants used to access those particular fields. (They will remain constant, no matter what setTimeInMillis you provide.)
How to solve it:
To get those particular fields you can use the .get(int field)-method, like this:
Log.d("Month--",""+cal.get(Calendar.MONTH));
As others have pointed out there are more convenient methods for formatting a date for logging. You could use for instance the SimpleDateFormat, or, as I usually do when logging, a format-string and String.format(formatStr, Calendar.getInstance()).
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date);
System.out.println(s);
TimeZone utc = TimeZone.getTimeZone("UTC"); // avoiding local time zone overhead
final Calendar cal = new GregorianCalendar(utc);
// always use GregorianCalendar explicitly if you don't want be suprised with
// Japanese Imperial Calendar or something
cal.setTimeInMillis(1306249409L*1000); // input need to be in miliseconds
Log.d("Date--",""+cal.get(Calendar.DAY_OF_MONTH));
Log.d("Month--",""+cal.get(Calendar.MONTH) + 1); // it starts from zero, add 1
Log.d("Year--",""+cal.get(Calendar.YEAR));
Java uses the number of milliseconds since 1st January 1970 to represent times. If you compute the time represented by 1306249409 milliseconds, you'll discover that it's only 362 days, so your assumptions are wrong.
Moreover, cal.DAY_OF_MONTH holds a constant. Use cal.get(Calendar.DAY_OF_MONTH) to get the day of month (same for other parts of the date).
use String.format which is able to convert long (milliseconds) to date/time string in different formats:
String str;
long time = 1306249409 * 1000L; // milliseconds
str = String.format("%1$tm/%1$td/%1$ty", time); // 05/24/11
str = String.format("%tF", time); // 2011-05-24 (ISO 8601)
str = String.format("Date--%td", time); // Date--24
str = String.format("Month--%tm", time); // Month--05
str = String.format("Year--%ty", time); // Year--11
documentation: format string.

Help Needed with Date Format in java

I have My Database data in this format
18-NOV-10
I have to pass the same format into java.util.Date like this
Date date = new java.util.Date(dateformater);
so that the result of java.util.Date is like this 18-NOV-10
Is this possible ??
I tried this way
String strDate = "12-NOV-07";
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MMM-yy");
Date date = sdfSource.parse(strDate);
System.out.println(date);
But i am getting the result as "Mon Nov 12 00:00:00 IST 2007 " which i want it only
12-NOV-07"
You can use java.text.DateFormat (actually SimpleDateFormat) to get you where you want to go, but maybe you shouldn't be storing the dates as strings in your database. It will do output and parsing.
SimpleDateFormat sdf =
new SimpleDateFormat("DD-MMM-YY");
Date parsed = sdf.parse(dateString);
See http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/
Once you get the Date, you can turn it into the format you want but it will be held in memory as a Date object. You can get it in the form you want using
String dateString = sdf.format(parsed);
As others have pointed out, you should probably store your dates as dates, not strings; nevertheless...
If you want to turn a Date back into a string in that format you can use the following:
DateFormat formatter = new SimpleDateFormat("dd-MMM-yy");
Date date = new Date();
String dateStr = formatter.format(date); // Gives "22-May-11"
If you need MAY instead of May, just use toUpperCase() on the resultant string.
DateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
Date d = sdf.parse("18-NOV-10");
Try System.out.println(sdfSource.format(date).toUpperCase()); instead. The Date object will always have a time component to it; there is no way to "disable" that feature. What you can do instead is to ignore it in your calculations and display. If all Date objects you use are set to the same time of the day, then you can safely ignore the effect of the time component in your comparisons. If you look carefully, the time component of your Date object is set to midnight.

Android Convert Central Time to Local Time

I have a MySql database that stores a timestamp for each record I insert. I pull that timestamp into my Android application as a string. My database is located on a server that has a TimeZone of CST. I want to convert that CST timestamp to the Android device's local time.
Can someone help with this?
Use getTimeZone.getDefault combined with according to the Android documentation.
public static synchronized TimeZone
getDefault ()
Gets the default time zone. Returns
the default time zone.
So since you know that CST is -6:00 from GMT, and you get a local timezone saying the user is +9:00 (Japan), you'd know to adjust your MySQL DB times by +15 hours (9 - (-6)). Or if they are in Miami (EST, -5), you would adjust by adding one hour (-5 - (-6)). If the are in Portland, Oregon, (PST -8), you would subtract 2 hours (-8 -(-6)).
So really you just need to get the local timezone offset and feed it into the basic equation: TimeZone.getDefault + 6 and you'll know what to add or subtract to your local DB. (+6 since -(-6) always works out to +6).
If I knew the first thing about writing Java, I'd go the extra step and write a bit of sample code, but alas, I'm only smart enough for scripts.
Crude Attempt at Java
I already said I have no idea how to do Java or object oriented anything, right?
Here's a crude attempt from just poking around the Android documentation. Any fine points or simple "Not even close" remarks welcome. Bear in mind that I figured out the right method and class already just from a quick search and I came up with a simple equation for converting the timezone offset for anywhere to CST, so I'm not a dunce, just someone who doesn't know when to leave well enough alone. Anyway, crude attempt:
System now = System.currentTimeMillis (); //Gets current local time in ms
TimeZone local_tz = TimeZone.getDefault(); //Gets current local TZ of phone
tz_offset_gmt = local_tz.getOffset(now)/3600000; // Get Offset in ms, divide by 3600000
tz_offset_cst = tz_offset_gmt + 6; // add offset to 6 to get current TZ offset to CST.
Anywhere close to how to do this in java?
Suppose you have a string of date in CST, parse it with timezone CST and then format it with the default timezone on your android.
String s = "2011-01-01 12:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("CST"));
Date timestamp = null;
try {
timestamp = df.parse(s);
df.setTimeZone(TimeZone.getDefault());
System.out.println(df.format(timestamp));
} catch (ParseException e) {
e.printStackTrace();
}
can't you simply convert the date with simpleDateFormat?
then you just define the structure of your incoming date like that (df) and transform it to the form you want (df):
private static DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
private static DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'at' HH:mm");
public void setyourDate(String yourDate) {
Date date2;
yourDate = getyourDate() + "" + yourDate;
try {
date2 = df.parse(yourDate);
yourDate = df2.format(date2);
} catch (ParseException e) {
}
this.yourDate = yourDate;
}
does it make sense?
This is an old question, but I want to write my answer. Assume, the timestamp you get from SQL is like the following format: yyyy-MM-dd'T'HH:mm:ss
public static Date convertStringToDate(String strDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("CST"));
return sdf.parse(strDate);
}

Categories