Current Time/Date Code Error - java

How do I get Current Time as this code is giving (Time-->Thu Jan 01 05:56:27 ACT 1970)??
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SS");
Date time = new Date();
String currentTime=timeFormat.format(time);
time=timeFormat.parse(currentTime);
System.out.println("Time-->"+time);
salesOrder.setOrderTime(time);

Class java.util.Date is not suitable for storing only a time-of-day (hours, minutes, seconds, milliseconds). Class Date is a timestamp, it contains a number of milliseconds since 01-01-1970, 00:00:00 GMT.
Use LocalTime from the Joda Time library for this instead.
Note: What you are doing in your code is first formatting a Date object to a String, and then parsing it back to a Date again, throwing away the day, month, year part. What you end up with is a Date object that's set to a number of hours, minutes, seconds and milliseconds since 01-01-1970, 00:00:00 GMT.

use DateFormat timeFormat = new SimpleDateFormat();
instead of
DateFormat timeFormat = new SimpleDateFormat("HH:MM:ss:SS");
The problem is in formatting. You have not provided the Day,year fieldr, thats why it is acting that way. Or You can use this with proper formatting :
DateFormat timeFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
EDIT:
Try this:
Calendar c = Calendar.getInstance();
c.setTime(time);
System.out.println(c.get(Calendar.YEAR)+ " "+c.get(Calendar.MONTH)+ " "+ c.get(Calendar.DAY_OF_MONTH));
Where time set in Calendar object is time that is not parsed/formatted using simpleDateFormat.
From calendar object, you can get individual month , day , year and use it the way you like, or you can just call c.getTime() to get the Date object.

Your format only contains hours and minutes and seconds. Given just a time of day with no date component, DateFormat.parse() does not fill in the current date; it falls back on the epoch of the system, "time zero", which is January 1, 1970. If you want a date string that can be turned back into a Date object, you need to include the year and month and day as well as the hour.

Related

Java: Compare dates on same timezone

Given:
SimpleDateFormat sd = new SimpleDateFormat ("yy-MM-dd hh:mm:ss.SSS");
sd.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = sd.parse("a date similar to now on local computer");
if I compare d.getTime() with new Date().getTime(), the values are different with more than one hour. Why?
Check your timezones. You are comparing a time that isn't in GMT.
You're explicitly setting your SimpleDateFormat to parse in GMT, which means that when you parse the current clock time, you're getting the moment of time when that time occurred, in the GMT time zone. If you're not in the GMT time zone, that won't be "now".
Date objects don't know anything about timezones - there is no explicit timezone information in a Date object. A Date object represents an "absolute" moment in time (it's a timestamp). This means you should not think of a Date object as "a date in a certain timezone" - it has no timezone.
Suppose that from some source you get a String that contains a date and time, without an explicit timezone mentioned in it, for example: 2014-12-16 17:30:48.382. Suppose that you know that this date and time is in the GMT timezone.
You could then parse it to a Date object with an appropriate SimpleDateFormat object:
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
// Set the timezone of the SimpleDateFormat to GMT, because you know the string
// should be interpreted as GMT
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
// Parse the String into a Date object
Date dateTime = fmt.parse("2014-12-16 17:30:48.382");
// Date object which is set to "now"
Date now = new Date();
// Compare it to "now"
if (dateTime.before(now)) {
System.out.println("The specified date is in the past");
} else if (dateTime.after(now)) {
System.out.println("The specified date is in the future");
} else {
System.out.println("The specified date is now");
}
If you want to print the date in a certain timezone, then do so by formatting it with a SimpleDateFormat set to the appropriate timezone.
DateFormat outfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
outfmt.setTimeZone(TimeZone.getTimeZone("EDT"));
// Will print dateTime in the EDT timezone
System.out.println(outfmt.format(dateTime));

Parsing time to calendar

I would like to set the timepart of a calendar. Here is what I'm doing
Calendar calNow = Calendar.getInstance();
Calendar endWait = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date d1 = null;
try {
d1 = sdf.parse("14:45");
}catch(ParseException ex){
logger.error("Error parsing time");
}
endWait.setTime(d1);
Date waitTo = endWait.getTime();
Date now = calNow.getTime();
The "now" variable is correct date and time, however the waitTo was expected to be the date of today and time 14:45, but is tomorrow at 02:45.
For me it is not giving tomorrow, but waitTo = Thu Jan 01 14:45:00 CET 1970.
The reason for this can be found in the javadoc of SimpleDateFormat:
This parsing operation uses the calendar to produce a Date. All of the
calendar's date-time fields are cleared before parsing, and the
calendar's default values of the date-time fields are used for any
missing date-time information. For example, the year value of the
parsed Date is 1970 with GregorianCalendar if no year value is given
from the parsing operation.
Calendar.setTime() will use the date and time information of the passed Date instance.
To only update the hours and minutes of the waitTo you can:
Calendar tmpCal=Calendar.getInstance();
tmpCal.setTime(d1);
endWait.set(Calendar.HOUR_OF_DAY,tmpCal.get(Calendar.HOUR_OF_DAY));
endWait.set(Calendar.MINUTE, tmpCal.get(Calendar.MINUTE));
This way the day, month, year part of the endWait will not be altered.

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.

Joda Time Not getting expected result

I have a date string of format MM/dd/yyyy that I am parsing using SimpleDateFormat
Now say the startDateString is 11/26/2012 for the code given below. I set the time zone to America/New_York
SimpleDateFormat df=new SimpleDateFormat("MM/dd/yyyy");
Date st = df.parse(startDateString);
Calendar startDate = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
System.out.println("BEFORE : Start Date :"+startDate.getTime());
startDate.setTime(st);
System.out.println("AFTER : Start Date :"+startDate.getTime());
DateTimeZone timezone = DateTimeZone.forID("America/New_York");
DateTime actualStartDate = new DateTime(startDate,timezone);
System.out.println("JODA DATE TIME "+ actualStartDate);
The outout of above code snippet:
BEFORE : Start Date :Tue Nov 27 12:26:51 IST 2012
AFTER : Start Date :Mon Nov 26 00:00:00 IST 2012 //ok it sets date to 26th
//with all time parameters as 0.
JODA DATE TIME 2012-11-25T13:30:00.000-05:00 // here the date and
// time parameter are changed
What my problem is when I create my actualStartDate like this :
DateTime actualStartDate = new DateTime(startDate,timezone);
The date changes to 25 and the time changes to 13:00:00
I think this is because of timezone zone difference between India and US (total -10:30 from IST Indian time)
What I want is JODA DATE TIME 2012-11-26T00:00:00.000-05:00
Do I manually set the parameters of time inside my startDate calendar instance to 0 ?
I suspect the problem is that you're parsing in your default time zone. This:
AFTER : Start Date :Mon Nov 26 00:00:00 IST 2012
shows that the instant in time you're using is midnight IST - not midnight in New York or in UTC. Currently IST is 18:30 in UTC, so the instant you're representing is 25-11-25T18:30:00Z.
When you convert that into New York time, you end up with 2012-11-25T13:30:00-05:00, which is exactly what Joda Time is doing.
I would strongly advise that:
You avoid using the Java libraries at all (that's where all the problems have come from here - both in parsing, and the result of Date.toString() confusing you)
You use LocalDate to represent a date, rather than DateTime. You're trying to represent a date after all, not an instant in time. This bypasses time zones entirely, as a date doesn't have a time zone.
Sample code:
import java.util.*;
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main (String[] args) {
String text = "11/26/2012";
DateTimeFormatter formatter =
DateTimeFormat.forPattern("MM/dd/yyyy")
.withLocale(Locale.US);
LocalDate date = formatter.parseLocalDate(text);
System.out.println(date);
}
}
Once you've got a LocalDate, if you want to find out the instant at which that day started in a particular time zone, you can use LocalDate.toDateTimeAtStartOfDay(DateTimeZone).

Unable to get the date in UTC format

I have written two functions - today() and todayUTC() - as:
public static Date today() {
Calendar cal = Calendar.getInstance();
return cal.getTime();
}
public static Date todayUTC() {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return cal.getTime();
}
But when I print the results of these functions using:
public void todayTest() {
Date date1 = OOTBFunctions.today();
System.out.println("today: "+date1);
Date dateUTC1 = OOTBFunctions.todayUTC();
System.out.println("todayUTC: "+dateUTC1);
}
I saw that both statements print the same value i.e.
today: Thu Aug 30 14:48:56 PDT 2012
todayUTC: Thu Aug 30 14:48:56 PDT 2012
Can anybody suggest what am I missing in UTC function that I am getting local timezone date.
Java uses the default Locale while printing and that is why you see that behavior. Use code like below to format and print it in the locale/format you want. Remember
When you create a Date object, it is always in UTC.
Display the date in the Locale of the user.
Store the date in UTC.
Code
final SimpleDateFormat sdf = new SimpleDateFormat("the format you want");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());
You doesn't need both today() and todayUTC() methods. keep and like below
public static Date nowInUTC()
{
return new Date();
}
You doesn't need to test anything.
Both of your methods will return the same value - a Date object doesn't have any notion of a time zone (unlike a Calendar). A Date just represents an instant in time, stored internally as the number of milliseconds since midnight January 1st 1970, UTC. Effectively, you've got two methods which are equivalent to:
return new Date(System.currentTimeMillis());
Date.toString() always uses the system default time zone.
If you want to maintain a date/time with a time zone, consider just using Calendar. If you want to format a particular instant in time in a time zone, just use SimpleDateFormat having set the time zone.
Ideally, change to use Joda Time instead of Date or Calendar though - it's a much cleaner API.

Categories