I have a XMLGregorianCalendar that I would like to convert to a Java Date object, but when I try to covert this:
2013-11-19T00:00:00-00:00
I always get a date with the value a day behind.
Mon Nov 18 17:00:00 MST 2013
I just want a date object containing 11/19/2013.
As commented above, the result you're getting is right - it's the same moment in time. Midnight UTC is 5PM MST the day before. Perhaps you should look into why your time is in "-00:00" instead of "-07:00" (MST)... but in the meanwhile, I suppose you could try this:
public static void main(String... args) throws DatatypeConfigurationException {
XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar("2013-11-19T00:00:00-00:00");
Calendar c = xcal.toGregorianCalendar();
c.setTimeZone(TimeZone.getDefault());
Date d = c.getTime();
System.out.println(d);
}
prints out Tue Nov 19 00:00:00 EST 2013, and will work for other times of day, not just midnight.
I just did this,
Date startDate = new Date(request.getStartTime().getYear(), request.getStartTime().getMonth(), request.getStartTime().getDay(), 0, 0, 0);
Related
Why does java make us write more code?
e.g:
long time = 1509694664442L;
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
c.getTime().setTime(time); // doesn't update the calendar's time!
System.out.println(c.getTime());
// but this does
Date d = c.getTime();
d.setTime(time);
c.setTime(d);
System.out.println(c.getTime());
Output:
Fri Jun 22 16:30:06 BRT 2018
Fri Jun 22 16:30:06 BRT 2018
Fri Nov 03 04:37:44 BRT 2017
Can someone explain why this happens since calendar.getTime() doesn't return a new instance of java.util.Date?
Calendar.getTime() returns a new Date instance, so trying to change the value on the returned object is futile, it has no effect on the Calendar instance.
Take a look at the source:
public final Date getTime() {
return new Date(getTimeInMillis());
}
This clearly shows that changing anything on the returned date doesn't change the calendar object itself.
You could make the change, then call calendar.setTime with the modified date to go around this.
Why does java make us write more code than the normal?
Because you are using the old and outdated date and time classes. java.time, the modern Java date and time API, allows not only terser but also clearer code:
long time = 1_509_694_664_442L;
Instant i = Instant.ofEpochMilli(time);
System.out.println(i);
Or, since you asked for brevity:
Instant.ofEpochMilli( 1_509_694_664_442L ).toString()
Output:
2017-11-03T07:37:44.442Z
For something more human readable (for some of us :-)
ZoneId zone = ZoneId.of("America/Recife");
Locale brazil = Locale.forLanguageTag("pt-BR");
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.FULL)
.withLocale(brazil);
String formatted = i.atZone(zone).format(formatter);
System.out.println(formatted);
sexta-feira, 3 de novembro de 2017 04:37:44 Horário Padrão de Brasília
Calendar.getTime()
…since calendar.getTime() doesn't return a new instance of java.util.Date?
It does exactly that. Here’s the implementation in JDK 10:
public final Date getTime() {
return new Date(getTimeInMillis());
}
Link
Oracle tutorial: Date Time explaining how to use java.time.
I have the method
public static void testDateFormat() throws ParseException {
DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
Date hora;
hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
}
The output is
0 0
Date Thu Jan 01 00:00:01 COT 1970
Seconds 18001
Why the number of seconds is 18001? I expected to get 1 second.
Because your Date has a TimeZone that is not UTC. It is, in fact, COT - which is UTC-5. And 5*60*60 is 18000 (or your result, plus one second). To get the value you expect, you could call DateFormat#setTimeZone(TimeZone) like,
DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // <-- Add this.
Date hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
Output is as you expect.
Edit
As noted in the comments, Date#getTime() per the Javadoc
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
And your Date of
Thu Jan 01 00:00:01 COT 1970
is equivalent to
Thu Jan 01 00:05:01 UTC 1970
and thus you get the 5 hour difference.
The answer by Elliott Frisch is correct.
Time-Only
But if you are working with time-only without date or time zone, then use a date-time library that can handle that explicitly rather than hacking the java.util.Date class.
LocalTime
Use either the Joda-Time library or the java.time package in Java 8. Both offer a LocalTime class.
LocalTime localTime = LocalTime.parse( "00:00:01" );
int minuteOfHour = localTime.getMinuteOfHour();
I'm trying to create a function that convert a timestamp to Date object.
My problem is that using this online tools i reach correctly to convert timestamp to date but using java it doesn't convert correctly.
This is what i try:
public static Date getDateFromUUID(UUID uuid) {
Calendar uuidEpoch = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
uuidEpoch.clear();
uuidEpoch.set(1582, 9, 15, 0, 0, 0);
long epochMillis = uuidEpoch.getTime().getTime();
long time = (uuid.timestamp() / 10000L) + epochMillis;
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
start.setTimeInMillis(time*1000);
end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
return end.getTime();
}
I'm trying using that uuid: a261ae00-2a9c-11b2-ae56-bcee7be23398
it correctly converts to timestamp : 1406412000
Using this:
Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Calendar end = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
start.setTimeInMillis(time*1000);
end.set(start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH),0,0,0);
return end.getTime();
I need to remove hours, minutes and seconds and take only years,months and days.
but it convert timestamp to
Sat Jul 26 02:00:00 CEST 2014
Instead of
Sun Jul 27 00:00:00 CEST 2014
what could be my mistake?
Thanks!
Your time zone if wrong. Notice that output is CEST but you set the calendar to UTC. The delta between these two is 2 hours. When you output the Date you need to set the timezone appropriately.
I am getting date in 28/12/2013 format, but I need current date in a String format,
like
Thursday, August 21
so that I can set over TextView,
Explain a bit, if you think something is necessary, I am new to Android Development.
You can always refer to the documentation.
http://developer.android.com/reference/java/util/Date.html
In the documentation you will find this:
Calendar.get(Calendar.MONTH)
public int getMonth () #old do not use
Returns the gregorian calendar month for this Date object.
Calendar.get(Calendar.YEAR
public int getYear () #old do not use
Returns the gregorian calendar year since 1900 for this Date object.
Calendar.get(Calendar.DAY_OF_WEEK)
public int getDay () #old do not use
Returns the gregorian calendar day of the week for this Date object.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMM dd");
String formatedDate = sdf.format(your_date);
At the moment I haven't programmed any android app, I'll do that in the future. But I have found that here. It may soulve your problem hopefully.
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateInstance(),
DateFormat.getDateTimeInstance(),
DateFormat.getTimeInstance(),
};
for (DateFormat df : formats) {
System.out.println(df.format(new Date(0)));
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(new Date(0)));
}
Produces this output when run on an en_US device in the America/Los_Angeles time zone:
Dec 31, 1969
Jan 1, 1970
Dec 31, 1969 4:00:00 PM
Jan 1, 1970 12:00:00 AM
4:00:00 PM
12:00:00 AM
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).