Formatting and parsing of Date and Strings in Java - java

I am just starting with Java (Android) and got stuck on a Date formatting issue.
I have a small Form where you can enter a project name and choose a Start date on a Calendar. The Startdate and Projectname gets than entered into the database, after that the pre-defined Tasks get than entered automatically into the database.
Task 1 Due Date is Startdate,
Task 2 is the Startdate plus x days = DueDate2,
Task 3 is The DueDate2 plus x days = DueDate3
I have now come up with the below Sourcecode and everything works besides that I get the wrong Format of my Date. For some reason, my Format is correct in newDateStr, but when I parse it again to be a Date Object, the format changes and is than incorrect. I can't see my mistake, anyone can help?
My understanding is:
Set the Date format of the date entered (curFormat)
Set the target Date format (postFormater)
Parse your Date which is a String at this time, to turn it into a date Object (use curFormat)
Format this date to get target date format (use postFormater), now its a String again
Parse this again to get it back to be a date which is needed for the calendar
Use calendar instance, setTime(here the formated date) and add the x days
Format the Date to get target date format (use postFormater), now its a String again
Because I need a Date Object again, I have to parse it again.
// The format of your input date string
SimpleDateFormat curFormater = new SimpleDateFormat("MM/dd/yyyy");
// The format of your target date string
SimpleDateFormat postFormater = new SimpleDateFormat("dd-MM-yyyy");
// The calendar instance which adds a locale to the date
Calendar cal = Calendar.getInstance();
// Parse the string (pro.getStart()) to return a Date object
Date dateObj = curFormater.parse(pro.getStart());
// Format the Date dd-MM-yyyy
String newDateStr = postFormater.format(dateObj);
// Parse the string to return a Date object
Date Startdate = postFormater.parse(newDateStr);
while (cur.isAfterLast() == false)
{
Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));
if (flag == false)
{
dateInString = Startdate;
flag = true;
}else{
cal.setTime(dateInString);
// add the extra days
cal.add(Calendar.DAY_OF_MONTH, delayTime);
// Format the Date dd-MM-yyyy
newDateStr = postFormater.format(cal.getTime());
// Parse the string to return a Date object
dateInString = postFormater.parse(newDateStr);
Log.i("newDateStr Format",newDateStr.toString()); // 29-11-2012
Log.i("dateInString parse",dateInString.toString()); // Thu Nov 29 00:00:00 GMT 2012
I hope someone sees my mistake. Thank you very much in advance !

A java.util.Date object does not have any format in it or memory of the format you used to parse it. The output of its toString method, and hence what you get as output from dateInString.toString() will always be in the default JDK format that you are seeing: Thu Nov 29 00:00:00 GMT 2012
You have to use a formatter to convert it into a formatted string whenever you want to display it. You cannot "Format the Date object" so to say. (UI frameworks tend to have built in facilities for doing this automatically.)

Don't keep converting the Calendar back to a string each time you loop. Keep one and just accumulate the delays in place...
SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
// Set the date once
cal.setTime(fmt.parse(pro.getStart()));
while(!cur.isAfterLast()) {
// Accumulate additional days
Integer delayTime = cur.getInt(cur.getColumnIndex("DelayTime"));
cal.add(Calendar.DAY_OF_MONTH, delayTime);
}
String endDate = fmt.format(cal.getTime());

Related

Time String to time representation Java

I have a string like this 210115 I want to represent it as 21:01:15 any ideas?.
I tried using Gregorian calendar but it adds date to it which I don't want
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
date = sdf.parse("210115");
}
catch(Exception e){
}
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());
Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15
Thanks.
To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.
In this case, it sounds like you might want to use something like
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );
So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.
LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format.
Simply do string operation as:
String time="210115";
String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
System.out.println(newtime);
you will get the required format.21:01:15

Difficulty parsing a string with SimpleDateFormat

I have a date string called allianceStartDate which has the value of
"1/7/2010"
I am trying to convert this date string to util Date object. The code which I have tried is as follows:
Date d = new SimpleDateFormat("dd/mm/yyyy").parse(allianceStartDate);
However the result of this operation is:
Fri Jan 01 00:07:00 GMT 2010
The desired result is a Date object in the format: "01/07/2010".
Thanks for any help offered.
It should be "dd/MM/yyyy" not "dd/mm/yyyy", We use mm for minutes not for Month in Java. You should use MM for month.
Read more about Java SimleDateFormat.
After parsing your initial text to obtain the Date object you will need to format it usig also a date formater in order to display it as a formatted text. Here is an exemple:
SimpleDateFormat SIMPLE_DATE_FORMATTER = new SimpleDateFormat("dd/MM/yyyy");
public String toSimpleDateFormat(Date d) {
return SIMPLE_DATE_FORMATER.format(d);
}

SimpleDateFormat returns wrong date value during parse

I m facing a problem:I want to get current time of GMT TimeZone in long.
I m using the following code as given below:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
As given in, above method
while formatting
String date = sdf.format(cal.getTime());
I m getting correct current time in GMT but as i do parsing by following code:
finalDate=sdf.parse(date);
Date got changed from current GMT time to 15:35:16 IST 2013 that is current time of my system.
I tried with Calendar as well in another way:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
but still getting date as current time of my System Thu Jan 23 15:58:16 IST 2014 Not getting GMT current time.
You've misunderstood how Date works. A Date doesn't have a time zone - if you use Date.toString() you'll always see the default time zone. The long value in a Date is purely the number of milliseconds since the Unix epoch: it doesn't have any concept of time zone or calendar system.
If you want to represent a date and time in a particular time zone and calendar, use Calendar instead - but for getting "the current date and time as a long" you can just use System.currentTimeMillis(), which again does not have anything to do with the system time zone.
Additionally, even if you did want to do manipulation like this, you shouldn't be using string conversions. You're not conceptually performing any string conversions, so why introduce them?
If your aim is to display (as a string) the current date and time in a particular time zone, you should just use something like:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
When working with date and time APIs - particularly bad ones like the Java Calendar/Date API - it's very important that you understand exactly what each value in your system represents.

Converting a date string from a timezone to different time zone

I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

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.

Categories