parse string to date and time but not getting appropriate parsing - java

i am attaching the code. In this code i am taking a string which is a date from a flat text file. It consist of AM/PM(12 Hour Format). When i am parsing it, it is not parsing well not parsing in 24 hour format. I want the time difference b/w the current time and the string from file. And because of AM/PM its not converting in 24 hour format. So its showing same time difference whether it is PM or AM. So tell me any fruitful suggestion if you have. I ll be really thankful to you guys.
public class Casting {
/**
* #param args
*/
static FileReader fw;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
fw = new FileReader("E://796F_log.txt");
BufferedReader pw =new BufferedReader(fw);
String last_Line_From_File="" ;
for (String message = pw.readLine(); message != null ; message = pw.readLine()) {
last_Line_From_File = message;
}
String[] array_Of_Data = last_Line_From_File.split("\\s") ;
String time = array_Of_Data[0]+" "+array_Of_Data[1]+" "+array_Of_Data[2] ;
System.out.println(time);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
Calendar cal = Calendar.getInstance();
String current_time = dateFormat.format(cal.getTime());
Date d1 = dateFormat.parse(time);
Date d2 = dateFormat.parse(current_time);
long total_time = d2.getTime()-d1.getTime();
total_time /= 1000 ;
System.out.println("current time "+d2.getHours()+":"+d2.getMinutes()+":"+d2.getSeconds()+"\n"+d1.getHours()+":"+d1.getMinutes()+":"+d1.getSeconds());
if(total_time <= 500)
{
System.out.println("working "+total_time);
}
else
System.out.println("nt working "+total_time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("did the smart thing or dumb thing");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("we did attempt closing");
}
}
}
}

The problem is your format:
"MM/dd/yyyy HH:mm:ss a"
The HH here means the 24-hour value. So it's expecting "19" for 7pm. It's almost always wrong to include both "HH" and "a" (the AM/PM designator) in the same format string.
You probably want either
"MM/dd/yyyy hh:mm:ss a"
or
"MM/dd/yyyy h:mm:ss a"
depending on whether you get things like "07:00:00 AM" or "7:00:00 AM".
If you're doing any significant amount of date/time work, I'd recommend using Joda Time instead of Date/Calendar, by the way.

Related

Calculating the age of two LocalDates

Code:
public String Calcage(){
int age = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date birth = sdf.parse(dateOfBirth);
Date d = new Date();
LocalDate birthday = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
age = Period.between(birthday, now).getYears();
} catch (ParseException e) {
e.printStackTrace();
}
return String.valueOf(age);
}
PROBLEM: It returns zero every time. The Date which I use for testing is 1985-01-07
If you are actually using 1985-01-07 it correctly returns 0 and should also throw a ParseException which will be caught from the catch block and the stacktrace will be printed.
Your code should work for 07.01.1985 and return 35.
if you want nevertheless to use 1985-01-07 you should edit the specified format to "yyyy-dd-MM" or "yyyy-MM-dd"

Having trouble adding times to generate time list

I'm trying to generate a time list in Java. I've read this as to how to add two times together. I wrote the code using floats before converting to using times so I know that the general format of the code works. This is the code that I'm having difficulty with:
public class Test2 {
public static void main(String[] args){
String time = "09:00";
String quarterHour = "00:15";
String halfHour = "00:30";
String quarterHour3 = "00:45";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
Date times;
Date temp;
long sum;
try {
times = timeFormat.parse(time);
while(times.before(timeFormat.parse("15:15"))){
System.out.println("Timelist: " + time);
if((times.equals(timeFormat.parse("10:15"))) || (times.equals(timeFormat.parse("13:45")))){
temp = timeFormat.parse(halfHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else if(times.equals(timeFormat.parse("11:45"))){
temp = timeFormat.parse(quarterHour3);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else{
temp = timeFormat.parse(quarterHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The result I get from that is simply 09:00. It goes through the loop once and ends.
I followed it through the debugger and what's happening is that when it adds the quarterHour to times it adds 12:15 and not the 00:15 as it's supposed to.
This seems to have something to do with me using 24 hour time as when I change the:
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
to:
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
It works - except that it goes into an eternal loop.
Question: How do I get it to add only 15 minutes to the time while using 24 hour format?
Use a Calendar, or if you're using Java 8 you might use the new java.time classes like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
LocalDateTime endTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timeFormat.parse("15:15").getTime()),
ZoneOffset.ofHours(0));
Instant instant = Instant.ofEpochMilli(timeFormat.parse(timeStr)
.getTime());
LocalDateTime time = LocalDateTime.ofInstant(instant,
ZoneOffset.ofHours(0));
while (time.isBefore(endTime)) {
time = time.plus(15, ChronoUnit.MINUTES);
Instant output = time.atZone(ZoneOffset.ofHours(0)).toInstant();
System.out.println(timeFormat.format(Date.from(output)));
}
} catch (Exception e) {
e.printStackTrace();
}
or, with the Calendar like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
Calendar cal = Calendar.getInstance();
cal.setTime(timeFormat.parse(timeStr));
Date when = timeFormat.parse("15:15");
while (cal.getTime().before(when)) {
cal.add(Calendar.MINUTE, 15);
System.out.println(timeFormat.format(cal.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
Add this line to your code:
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
immediately after you declare timeFormat.
It fixes your problem on my computer.

Android parsing String to Date with SimpleDateFormat

I have String dateOrder= '2014-09-28' , i want to change format with SimpleDateFormat. but this is cannot formated.. how to solve ?
this my code
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yy");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
dateOrder = date.format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try changing the first line to
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
You can use this for the parse. Then you need another SimpleDateFormat("dd/MM/yy") for formatting the new version.
The key point is that the parsing needs to be done with one pattern, and the formatting needs to be done with another. So rather than just creating one SimpleDateFormat instance, you need two, with different patterns: one for parsing, and one for formatting.
I believe you want something like this:
//first create an object that will parse your date as you have it ie 2014-09-28
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
String dateOrder = fill_order_in.get(Variabel.KEY_DATE_ORDER);
try {
Date d = date.parse(dateOrder);
//then use a different object to format the date as you want it ie 9/28/2014
dateOrder = new SimpleDateFormat("dd/MM/yy").format(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

SimpleDateFormat and Date Comparison not given correct ouput

try {
Date sysDate = new SimpleDateFormat("dd/mm/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/mm/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above is my following code snippet to check two dates which is greater or not.
When I am giving :
sysdate=12/9/2012 and userdate=11/9/2012 or 10/8/2012 or 15/9/2011 it is giving the correct output
But when I am giving :
sysdate=12/9/2012 and userdate=13/8/2012 or 15/7/2012 or 16/6/2012 it is giving incorrect output.
To my analysis I have come to this point if I choose any month between Jan' 12 to Aug '12 and select the day_of_month(i.e. 0,1,2,...,31) more than the current day_of_month (in this case 12), I always get an incorrect output.
Please suggest any possible solution.
The problem is the pattern which should be "dd/MM/yyyy" (with capital "MM" for month) instead of "dd/mm/yyyy" (with small "mm" which means minutes).
So, it should be as follows -
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date sysDate = df.parse(_sysDate);
Date userDate = df.parse(_userDate);
//...
try {
Date sysDate = new SimpleDateFormat("dd/MM/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/MM/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Date pattern is wrong dd/MM/yyyy instead of dd/mm/yyyy.
see this data format change like this dd/MM/yyyy in place of dd/mm/yyyy.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Using SimpleDateFormat in a for loop on a list of objects

My app crashes whenever I try to do this:
for (CalendarEvent event : this.ListofEvents){
String myDate = new String(event.getDate());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
theDate = format.parse(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(theDate.getDate());
}
If I just print event.getDate() as a test, it displays all the dates. But when I try to format each date I'm assuming it locks up the phone resources. It's a fairly large List with many entries.
Perhaps there's a better method of getting the day, month, and year without taking up all the resources.
Why are you creating a DateFormat inside the loop? You create it, use it, and then it goes out of scope for GC in the next iteration.
Move it outside the loop:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
format.setLenient(false);
for (CalendarEvent event : this.ListofEvents){
// what does event.getDate() return? A java.util.Date? If yes, why are you doing this at all?
String myDate = new String(event.getDate());
try {
theDate = format.parse(myDate);
System.out.println(theDate.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
}

Categories