Parsing time to calendar - java

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.

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));

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.

how to get any specific date of current year

Hi I was wondering if there was any way using Jav's Date class or and Joda Time classes to get any specific day of this year. For example if I want the date 12/31/2013. The reason why this is a problem is because I am giving a string representation of someone's birthday lets say "12311991" "MMddyyyy" and I want to convert this to be a Date which has month 12 day 31 and year 2013.
Can anyone help me on this?
I am using the DateMidnight Joda time class and I parse the string into a date using Simple Formatter but I was wondering if there was any way to set the year to be a specific year.
Start by converting the String to a Date...
String dateString = "12311991";
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
Date date = sdf.parse(dateString);
Which results in ....
Tue Dec 31 00:00:00 EST 1991
Next, use Calendar to modify the year
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.YEAR, 2013);
date = cal.getTime();
Which results in...
Tue Dec 31 00:00:00 EST 2013
If you want to implement using JodaTime you can do as below. Format using DateTimeFormatter to get DateTime and then with DateTime#withYear(int) method, year can be changed.
String dob = "12311991";
DateTimeFormatter fmt = DateTimeFormat.forPattern("MMddyyyy");
DateTime dt = fmt.parseDateTime(dob).withYear(2013);
System.out.println(dt);
Try using Calendar
set(int year,
int month,
int date)
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#set(int, int, int)
Just use SimpleDateFormat (click me to see all format patterns).
String string = "12/31/2013";
Date date = new SimpleDateFormat("dd/mm/yyyy", Locale.ENGLISH).parse(string);
System.out.println(date);
java.time
The other answers are outdated. The old date-time classes, as well as Joda-Time, have been supplanted by the java.time framework built into Java 8 and later.
The LocalDate class truly represents a date-only value without time-of-day and without time zone (lacking in the original date-time classes).
String input = "12311991";
DateTimeFormatter formatter = DateTimeFormatter.forPattern("MMddyyyy");
LocalDate localDate = LocalDate.parse( input , formatter ); // 1991-12-31
LocalDate differentYear = localDate.withYear( 2013 ); // 2013-12-31

Current Time/Date Code Error

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.

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