Java Date issue - java

I am using GregorianCalander and when i tried to get todays date using the following code i am getting a date which is backdated to one month. The code i have used is as follows.
Calendar gcal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = getTime(gcal);
//date = dateFormat.format(calendar.getTime());
System.out.println("Today: " + today);
Please help me to solve this issue.
The output is :
Today: Thu Apr 28 00:00:00 NZST 2011
EDIT
private Date getTime(Calendar gcal) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String day = form_helper.round(gcal.get(GregorianCalendar.DAY_OF_MONTH));
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH));
String year = form_helper.round(gcal.get(GregorianCalendar.YEAR));
String date = day + "/" + month + "/" + year;
System.out.println(sdf.parse(date));
return sdf.parse(date);
} catch (ParseException ex) {
Logger.getLogger(timesheet_utility.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}

I think internal numbering of months starts with 0, not 1. So, you probably need to somewhere add +1.
Edit: after you showed some more code: The needed change is
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH) + 1);

What does the getTime() method do? Remember that in Java, the constants for the month begin at 0 and not at 1, so Calendar.JANUARY == 0.
EDIT
Since you posted the code for getTime() I think this is the problem:
gcal.get(GregorianCalendar.MONTH) returns the month value that Java internally stores, that is, a 0-indexed month value so a value for "May" would actually be the integer "4".
When the value "4" is put back into the date parser, "April" results, since the parser interprets dates as a human would. So you simply have to add 1 to this value to ensure the parsing happens properly.

If you want a Date object that represents 12:00AM (or 00:00) for today, why not just do:
private Date getTime() {
Calendar gcal = new GregorianCalendar();
gcal.set(Calendar.HOUR_OF_DAY, 0);
gcal.set(Calendar.MINUTE, 0);
gcal.set(Calendar.SECOND, 0);
gcal.set(Calender.MILLISECOND, 0);
return gcal.getTime();
}

Here's my attempt:
package forums;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Deepak
{
public static void main(String[] args) {
try {
(new Deepak()).run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
Calendar calendar = new GregorianCalendar();
Date today = calendar.getTime();
System.out.println("Today: " + today);
}
}
and the output is the expected:
Today: Sat May 28 22:00:52 EST 2011

Related

Java Date not working correctly

Let's have the following:
Date inDbDate = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
inDbDate = sdf.parse("2015-09-27 23:24:28.035");
Now, when I output the inDbDate I receive the following:
Sun Sep 27 23:24:28 EEST 2015
So, If I have two dates with millisecond differences, there would be no way to find out or to display it.
How do I compare two Dates with this format - 2015-09-27 23:24:28.035 ?
If you want to compare two Date variables, there are some methods provided after(), before(), equals().
private void someMethod(){
final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date firstDate = new Date();
Date secondDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
firstDate = sdf.parse("2015-09-27 23:24:28.035");
secondDate = sdf.parse("2015-09-27 23:24:28.036");
} catch (ParseException pe) {
pe.getMessage();
}
if(firstDate.after(secondDate)) {
System.out.println("The first date is after the second date");
} else{
System.out.println("The first date is before the second date");
}
}
You can copy and paste the above method into your IDE, then try changing the time in the Date variables and see what the outcome is as well as changing the check performed in the if statement.
If you look at the values in one of the Date objects in your debugger you can see the milliseconds are there, just not shown when printed out in a certain format.
1/ you should parse inDbDate with date format ==> inDbDate = sdf.parse("2015-11-11 23:24:28.035");
2/ you can now compare the two dates
if (inDbDate.compareTo(new Date()) > 0) {
System.out.println("inDbDate is after the current date !!");
}
3/ if you want to display, you format it
System.out.println("current time = " + sdf.format(new Date()));

Java : calculate remaining time compared to current time

I have a string in format :
2015-10-01 02:00
I want to print the remaining time compared to current time in Java, it should print in format :
It remains 1 day 4 hours 25 minutes
How could I do that ? Thanks for any ideas.
I got it working! Could you withdraw all the unvotes please ?
public static void calculateRemainTime(String scheduled_date){
// date format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// two dates
java.util.Date scheduledDate;
Calendar current = Calendar.getInstance();
java.util.Date currentDate;
String current_date = format.format(current.getTime());
try {
scheduledDate = format.parse(scheduled_date);
currentDate = format.parse(current_date);
long diffInMillies = scheduledDate.getTime() - currentDate.getTime();
long diffence_in_minute = TimeUnit.MINUTES.convert(diffInMillies,TimeUnit.MILLISECONDS);
System.out.println(diffence_in_minute);
} catch (ParseException e) {
e.printStackTrace();
}
}

While formatting GMT time to GMT+01:00 an extra hour is being added

I am facing the problem of an hour being added to the time after formating only in GMT+01:00.
Here is how i am doing it:
private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
// Change Start date according to the Locale time
formattor.setTimeZone(TimeZone.getTimeZone("GMT"));
date1 = formattor.parse("2015-03-26 11:17:41");
formattor.setTimeZone(TimeZone.getDefault());
String start = formattor.format(date1);
// Change End date according to the Locale time
formattor.setTimeZone(TimeZone.getTimeZone("GMT"));
date1 = formattor.parse("2015-03-26 13:17:00");
formattor.setTimeZone(TimeZone.getDefault());
String end = formattor.format(date1);
System.out.println(start + " - " + end);
} catch (ParseException e) {
e.printStackTrace();
}
Output:
2015-03-26 12:17:41 - 2015-03-26 14:17:00
I am facing the same problem with Joda-Time.
I have tested it with GMT+01:00, West Africa Standard Time
That's very obvious since your getDefault () would make the Timezone to GMT+01:00 hence you're seeing the same. Reframe the question if this is not what you're expecting.

how to convert the a string to a calendar object in java

I have the below string which is input to my method
String xymessage="Your item(s) will be ready Today for pickup by 10:00 a.m. ";
Now how can i convert this string to a calendar object.
I was able to extract the day ie. whether its "today" or "tomorrow". And also the time ie. "10:00 a.m."
using these two parameters as input ie. today and 10:00 a.m. will it be possible for me to convert it to a calendar object?
Sample code snippet:
String xymessage="Your item(s) will be ready Today for pickup by 10:00 a.m. ";
if(null != xyMessage){
//removing empty spaces.
xyMessage=xyMessage.trim();
LOGGER.debug("sellerId:"+delivSeller.getSellerId()+" and xymessage:"+xyMessage);
if(xyMessage.contains("Today")){
//this means its today
String[] xyArray = xyMessage.split("pickup by");
if(xyArray.length == 2){
String timeVal=xyArray[1];
}
}else{
//this means its tomorrow
}
}
Use Calendar cal = Calendar.getInstance() to get a calendar object with the current date and time. Using the add(), get(), and set() methods, you can set the calendar object correctly. For instance, to change the date to tomorrow's, you could do: cal.add(Calendar.DAY_OF_MONTH, 1);
To set the hour, cal.set(Calendar.HOUR, hr); where hr was initialized with the hour to be set. Similarly for minutes, etc.
You can use SimpleDateFormat for the format you want. But as you are having a.m. or p.m. instead of plain simple AM/PM, it makes a bit of complication.
Check the below code if it helps for "today" condition :
Here variable 'time' is what you have extracted like "10:00 a.m."
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = new Date();
String timeArray[]=time.split(" ");
String minArray[]=timeArray[0].split(":");
date.setHours(Integer.parseInt(minArray[0]));
date.setMinutes(Integer.parseInt(minArray[1]));
if(!timeArray[1].startsWith("a")){
date.setHours(date.getHours()+12);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Administrator
*/
public class Test {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
Calendar today = Calendar.getInstance();
Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
String xyMessage = "Your item(s) will be ready Today for pickup by 10:00 a.m. ";
if (null != xyMessage) {
//removing empty spaces.
xyMessage = xyMessage.trim();
if (xyMessage.contains("Today")) {
//this means its today
String[] xyArray = xyMessage.split("pickup by ");
String time = xyArray[1].replace(".", "");
today.set(Calendar.HOUR_OF_DAY, sdf.parse(time).getHours());
System.out.println("calendar:" + finalFormat.format(today.getTime()));
} else {
//this means its tomorrow
String[] xyArray = xyMessage.split("pickup by ");
String time = xyArray[1].replace(".", "");
tomorrow.set(Calendar.HOUR_OF_DAY, sdf.parse(time).getHours());
System.out.println("calendar:" + finalFormat.format(tomorrow.getTime()));
}
}
}
}
just use SimpleDateFormat("hh:mm aa")
Try below code.
String val = "10:00 a.m";
val = val.replace(".", "");
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Calendar temp = Calendar.getInstance();
temp.setTime(dateFormat.parse(val));
Calendar cal = Calendar.getInstance();
if ("tomorrow".equalsIgnoreCase("YOUR_STRING")) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
cal.set(Calendar.HOUR_OF_DAY, temp.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, temp.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.DAY_OF_MONTH) + ":"
+ (cal.get(Calendar.MONTH) + 1) + ":"
+ cal.get(Calendar.HOUR_OF_DAY) + ":"
+ cal.get(Calendar.MINUTE));
}

Pick day, month and year out file.lastModified();

I know how to use file.lastModified();.
When I println that I get (for example): Sat Mar 17 09:24:33 GMT+01:00 2012.
But is it possible that I only get the day, month and year as numbers, for example: 17 03 2012
Is their a way to do this, maybe a filter, or an other function to get last modified date in numbers?
is file a java.io.File object?
lastModified should return time in milliseconds. You can create a Date object with the lastModified return value and the format the output with a SimpleDateFormat
Date date = new Date(file.lastModified());
System.out.println(date);
SimpleDateFormat sdf = new SimpleDateFormat("d M y");
System.out.println(sdf.format(date));
You can use SimpleDateFormat class, i.e.
package com.example.file;
import java.io.File;
import java.text.SimpleDateFormat;
public class GetFileLastModifiedExample
{
public static void main(String[] args)
{
File file = new File("\\somefile.txt");
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("After Format : " + sdf.format(file.lastModified()));
}
}
Try this,
long longDate = file.lastModified();
Date date = new Date(longDate);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
String newDate = formatter.format(date);
System.out.println("Formatted date " + newDate);
according to the documentation
File.lastModifed()
should return a long value representing the time the file was last modified, measured in milliseconds since the epoch. Yon can use the long value in conjunction with Calendar
Calendar rightNow = Calendar.getInstance()
rightNow.setTimeInMillis(longValue)
and use rightNow.get(...)
to retrive day, month and year

Categories