I have this code:
Date dt = new Date(100000000000L);
DateFormat[] dtformat = new DateFormat[6];
dtformat[0] = DateFormat.getInstance();
dtformat[1] = DateFormat.getDateInstance();
dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
for(DateFormat dateform : dtformat)
System.out.println(dateform.format(dt));
I don't know what is the meaning of this code (the 100000000000L) function:
Date dt = new Date(100000000000L);
DateFormat[] dtformat = new DateFormat[6];
Can someone tell me? Because I want to replace the time to the 24 July 1998
The docs clearly state that the parameter for constructing a Date is:
milliseconds since January 1, 1970, 00:00:00 GMT not to exceed the milliseconds representation for the year 8099. A negative number indicates the number of milliseconds before January 1, 1970, 00:00:00 GMT.
So, 0 would represent Midnight 1 Jan, 1970.
However, if I were you, I would stop using Date and use LocalDate which is much easier to use.
Date(long date)
Its a parameterized constructor of Date Class in java which Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
For more information you can refer to below link
Date Class in Java
john16384 in his answer says
if I were you, I would stop using Date and use LocalDate, which is
much easier to use.
I agree. Here’s how:
LocalDate dt = LocalDate.of(1998, Month.JULY, 24);
DateTimeFormatter[] dtformat = {
DateTimeFormatter.BASIC_ISO_DATE,
DateTimeFormatter.ISO_LOCAL_DATE,
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL),
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG),
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
};
for (DateTimeFormatter dateform : dtformat) {
System.out.println(dt.format(dateform));
}
Note how straightforward it is to create the desired date (to do the same with an old-fashioned Date object, you would be required to go through a class named Calendar). I am using an array initializer instead of explicitly assigning an object to each element of the array. It’s simpler.
On my computer (Danish locale) the above code prints:
19980724
1998-07-24
24. juli 1998
24. juli 1998
24-07-1998
24-07-98
If you want to control the locale explicitly (sometimes a good idea to avoid surprises), you may use DateTimeFormatter.withLocale(), for example DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(new Locale("Indonesian")) or DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(Locale.ROOT).
Related
I have a time stamp like this(form a json response) :
"/Date(1479974400000-0800)/"
I'm trying this function to convert time stamp into date:
public String getDate() {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
How to convert this Timestamp into Date format?
Parse directly into an OffsetDateTime
Java can directly parse your string into an OffsetDateTime. Use this formatter:
private static final DateTimeFormatter JSON_TIMESTAMP_FORMATTER
= new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendOffset("+HHMM", "Z")
.appendLiteral(")/")
.toFormatter();
Then just do:
String time = "/Date(1479974400000-0800)/";
OffsetDateTime odt = OffsetDateTime.parse(time, JSON_TIMESTAMP_FORMATTER);
System.out.println(odt);
Output is:
2016-11-24T00:00-08:00
In your string 1479974400000 is a count of milliseconds since the epoch of Jan 1, 1970 at 00:00 UTC, and -0800 is an offset of -8 hours 0 minutes from UTC (corresponding for example to Pacific Standard Time). To parse the milliseconds we need to parse the seconds since the epoch (all digits except the last three) and then the millisecond of second (the last three digits). By specifying the width of the milliseconds field as 3 Java does this. For it to work it requires that the number is at least 4 digits and not negative, that is not within the first 999 milliseconds after the epoch or earlier. This is also why I specify in the formatter that the seconds must not be signed.
I specified Z for offset zero, I don’t know if you may ever receive this. An offset of +0000 for zero can still be parsed too.
Original answer: parse the milliseconds and the offset separately and combine
First I want to make sure the timestamp I have really lives up to the format I expect. I want to make sure if one day it doesn’t, I don’t just pretend and the user will get incorrect results without knowing they are incorrect. So for parsing the timestamp string, since I didn’t find a date-time format that would accept milliseconds since the epoch, I used a regular expression:
String time = "/Date(1479974400000-0800)/";
Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
Matcher m = pat.matcher(time);
if (m.matches()) {
Instant i = Instant.ofEpochMilli(Long.parseLong(m.group(1)));
System.out.println(i);
}
This prints:
2016-11-24T08:00:00Z
If you want an old-fashioned java.util.Date:
System.out.println(Date.from(i));
On my computer it prints
Thu Nov 24 09:00:00 CET 2016
This will depend on your time zone.
It is not clear to me whether you need to use the zone offset and for what purpose. You may retrieve it from the matcher like this:
ZoneOffset zo = ZoneOffset.of(m.group(2));
System.out.println(zo);
This prints:
-08:00
The zone offset can be used with other time classes, like for instance OffsetDateTime. For example:
OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
System.out.println(odt);
I hesitate to mention this, though, because I cannot know whether it is what you need. In any case, it prints:
2016-11-24T00:00-08:00
If by date you mean Date instance, then you can do this:
new Date(Long.parseLong("\/Date(1479974400000-0800)\/".substring(7, 20)));
I assume this info in holding the String representing an Epoch and a TimeZone
"/Date(1479974400000-0800)/"
you need to get rid off the all the not necessary parts and keeping only the
1479974400000-0800
then the epoch is 1479974400000 and I guess the Timezone is 0800
then do:
String[] allTimeInfo = "1310928623-0800".split("-");
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
Date time = new java.util.Date(Long.parseLong(allTimeInfo[0]));
System.out.println(time);
System.out.println(timeZoneFormat.format(time));
The solution works
for me is like this:
String str = obj.getString("eventdate").replaceAll("\\D+", "");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new java.util.Date(Long.parseLong(upToNCharacters));
// System.out.println(time);
model.setDate(String.valueOf(timeZoneFormat.format(time)));
Use time variable where you want
This is continuation to one of my previous question where I am not able to parse the date which is resolved now. In the below code, I have a date string and I know the time zone for the date string even though the string itself doesn't contain it. Then I need to convert the date into EST time zone.
String clientTimeZone = "CST6CDT";
String value = "Dec 29 2014 11:36PM";
value=StringUtils.replace(value, " ", " ");
DateTimeFormatter df = DateTimeFormat.forPattern("MMM dd yyyy hh:mma").withZone(DateTimeZone.forID(clientTimeZone));
DateTime temp = df.parseDateTime(value);
System.out.println(temp.getZone().getID());
Timestamp ts1 = new Timestamp(temp.getMillis());
DateTime date = temp.withZoneRetainFields(DateTimeZone.forID("EST"));//withZone(DateTimeZone.forID("EST"));
Timestamp ts = new Timestamp(date.getMillis());
System.out.println(ts1+"="+ts);
When I am running the code I am expecting ts1 to remain same and ts to be up by 1 hr. But iam getting below which I don't understand. I thought EST is one hour ahead of CST and so if it is 11 in CST, it should be 12 in EST. Also there seems to be offset by about eleven and half hours. Any clues on what I am missing.
2014-12-30 11:06:00.0=2014-12-30 10:06:00.0
I think the below code will help you.
String clientTimeZone = "CST6CDT";
String toStimeZone = "EST";
String value = "Dec 29 2014 11:36PM";
TimeZone fromTimeZone = TimeZone.getTimeZone(clientTimeZone);
TimeZone toTimeZone = TimeZone.getTimeZone(toStimeZone);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(fromTimeZone);
SimpleDateFormat sf = new SimpleDateFormat("MMM dd yyyy KK:mma");
Date date = sf.parse(value);
calendar.setTime(date);
System.out.println(date);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
System.out.println(calendar.getTime());
Copied from : http://singztechmusings.wordpress.com/2011/06/23/java-timezone-correctionconversion-with-daylight-savings-time-settings/
The method withZoneRetainFields() preserves the fields in the timezone CST (= UTC-06) hence your local timestamp (as LocalDateTime) but combines it with a different timezone (EST = UTC-05) which is one hour ahead in offset and result in a different instant. You should it interprete it this way: The same local time happens one hour earlier in New York compared to Chicago.
The rule is to subtract positive offsets and to add negative offsets in order to make timestamp representations of instants comparable (normalizing to UTC offset).
Alternatively: Maybe you don't want this but want to preserve the instant instead of the local fields. In this case you have to use the method withZone().
Side notice: Effectively, you compare the instants represented by the variables temp and date and finally use your default timezone to print these instants in the JDBC-escape-format (explanation - you implicitly use Timestamp.toString()). I would rather recommend to use a dedicated instant formatter for this purpose or simpler (to have the offsets in focus):
System.out.println(temp.toInstant() + " = " + date.toInstant());
I am having trouble formatting date in java.
I have a shopping class that has item name in string, quantity in int and a date in Date.
In the run class I am trying to run this query.
Date date = new Date(202020);
SimpleDateFormat dateformat = new SimpleDateFormat("dd-mm-yy");
String date1 = dateformat.format(date);
Shopping shoplist1 = new Shopping ( "iphone", 2, date);
When I try to create a new shopping entery with the date the date does not format. I don't know why but it gives me Thu Jan 01 01:03:22 GMT 1970.
You are using wrong Date class constructor:
Date date = new Date(202020);
Means that you are trying to allocate a Date object and initialize it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
You should use something like this:
Shopping shoplist1 = new Shopping ("iphone", 2,
new SimpleDateFormat("dd-MM-yy").parse("20-20-20"));
Read documentation to get more difference between DateFormat#parse(...) and DateFormat#format(...)
From your comment :
"I tried to add date 1, but it wouldn't allow it. It says string can not be converted to date"
You are passing string to your constructor but looks like it can take java.util.Date object
Shopping shoplist1 = new Shopping ( "iphone", 2, date);
Change your constructor signature to take a String object
OR
Pass the date object and perform the formatting in any other relevant location
change SimpleDateFormat dateformat = new SimpleDateFormat("dd-mm-yy"); to SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");
if I clearly remember small mm mean minutes not month
Read this post about date formatting
and also as say #zvzdhk, you incorrectly use date constuctor.
You create the date instance from a timestamps (milliseconds from 1970). I suppose that is not what you are trying to do.
You format the date into a string and pass the date. If you want to use the formatted date, you have to pass the string.
I have following method which convert my custom DMY (date,month,year) object to Date.
public static Date serverCreateDateFromDMY(DMY pDMY, TimeZone pTimeZone)
{
Calendar vCalendar = Calendar.getInstance(pTimeZone);
vCalendar.set(Calendar.YEAR, pDMY.getYear());
// Below line is because DMY month counts are 1-indexed
// and Date month counts are 0-indexed
vCalendar.set(Calendar.MONTH, pDMY.getMonthOfYear() - 1);
vCalendar.set(Calendar.DAY_OF_MONTH, pDMY.getDayOfMonth());
System.out.println(vCalendar.getTime());
TimeUtilsServer.zeroCalendarHoursAndBelow(vCalendar);
System.out.println(vCalendar.getTime());
return vCalendar.getTime();
}
public static void zeroCalendarHoursAndBelow(Calendar pToZero)
{
pToZero.set(Calendar.HOUR_OF_DAY, 0);
pToZero.set(Calendar.MINUTE, 0);
pToZero.set(Calendar.SECOND, 0);
pToZero.set(Calendar.MILLISECOND, 0);
}
to serverCreateDateFromDMY() method, I am passing these arguments : DMY=20120424, and TimeZone is : America/New_York. Application is running locally in my timezone which is IST.
based in above inputs, following output is printed.
Tue Apr 24 14:43:07 IST 2012
Tue Apr 24 09:30:00 IST 2012
so as you see that in last output time is not zeroed out. any suggestions please?
#Marko, yes I come to know about DateFormat and I tried following example. but still date is printed with time and not zeroing out.
TimeZone tz = TimeZone.getTimeZone("America/New_York");
Calendar vCalendar = Calendar.getInstance(tz);
vCalendar.set(Calendar.YEAR, 2012);
vCalendar.set(Calendar.MONTH, 4 - 1);
vCalendar.set(Calendar.DAY_OF_MONTH, 24);
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(tz);
System.out.println(df.format(vCalendar.getTime()));
vCalendar.set(Calendar.HOUR_OF_DAY, vCalendar.getActualMinimum(Calendar.HOUR_OF_DAY));
vCalendar.set(Calendar.MINUTE, vCalendar.getActualMinimum(Calendar.MINUTE));
vCalendar.set(Calendar.SECOND, vCalendar.getActualMinimum(Calendar.SECOND));
vCalendar.set(Calendar.MILLISECOND, vCalendar.getActualMinimum(Calendar.MILLISECOND));
System.out.println(df.format(vCalendar.getTime()));
java Date / Time API have a bad design from the time of its creation. Maybe you should take a look at some library - for example this which hides JDK API deficiencies - http://joda-time.sourceforge.net/
Internally, Date and Calendar objects are stored in UTC. When you set the fields to 0, the Calendar is updated in UTC.
When you ask the Calendar for the time, it then converts the Date to your desired Timezone, hence the difference.
... and you are 9:30h ahead of NY time. You set the time to midnight NY time and read it out as time in your zone. Note that getTime returns a Date, which is not timezone-configurable. You'll need DateFormat if you want to specify the timezone for which you print the result.
Looking for a bit of help with taking a dat from a DatePicker Widget and storing it in an sqlite database within the app. I have the following code:
java.util.Date utilDate = null;
String y = Integer.toString(date.getDayOfMonth()) + "/" + (date.getMonth()+1) + "/" + Integer.toString(date.getYear());
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyy");
utilDate = formatter.parse(y);
java.sql.Date z = new java.sql.Date(utilDate.getDate());
x = z.toString();
Log.v("The date: ", x);
}
Where date is the DatePicker widget. If I output the utilDate variable (i.e. the Java version of date) using logCat it seems to work fine and gives me a format like: Tue Jan 04 00:00:00 GMT 2011 which I am expecting but using the code above to get the sql version of the date, it always gives me the date 1970-01-01. I'm pretty sure the solution is very simple but I just can't see it.
This part: utilDate.getDate() is wrong.
Quote from Javadoc:
Returns the day of the month represented by this Date object. The value returned is between 1 and 31 representing the day of the month that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
So, you get a number between 1 and 31, and you expect a long that represents number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.
Use
java.sql.Date z = new java.sql.Date(utilDate.getTime());
and everything should be OK.