Time stamp not converted in date properly in java - java

I'm trying to convert a time stamp into date using this code:
String str = "14799744000000800";//last four digit is time zone
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date time = new java.util.Date(Long.parseLong(str));
System.out.println(timeZoneFormat.format(time));
But it prints '21-03-470955 00:00:00' instead of 21-03-2016 00:00:00.
As you can see year part is not converted properly.how to fix this?

The current milliseconds value is 1481007881541, so 14799744000000800 does seem to be really in the future.
Edit
As per your later comments, you could just remove last four digit from string.

Related

How to add X number of days to current date and format as UTC

I'm trying to get the current date/time add a number of days and display in a UTC format.
Current output is like this: 2019-05-09T11:11:4226
See code for below, I think I'm maybe taking the wrong approach to this.
int NumDaysInFurure = 1;
Date currentDate = new Date();// get the current date
SimpleDateFormat daateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
daateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = ""+dateFormat.format(currentDate) + NumDaysInFurure;//add one day to the current date
Log.i("the future date is", date);
Starting from Java8, this would be a better approach:
DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss").format(LocalDateTime.now().plusDays(1))
to break it down:
LocalDateTime.now()
returns an instance of LocalDateTime with the current date and time.
You add one day (using the plusDays(Long days)) method.
The result of this, you format using a DateTimeFromatter.
The result of the complete is a String with the right date/format.

How to convert Timestamp into Date format in java

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

JSON date to formatted JAVA date [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 6 years ago.
I am trying to get dd.MM.yyyy and hh:mm from 1436536800 but only the time is correct, the date is completely wrong. I don't really understand how this is supposed to work
int dt = time.getInt("start")*1000;
Date date = new Date(dt);
startDate = dateFormat.format(date);
If time.getInt("start") is a valid unix timestamp, you must add "000" to the number. Example: 1436536800 * 1000 = 1436536800000. Then you can use the timestamp to get a Date:
final Date date = new Date(Long.parseLong("1436536800000"));
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm");
System.out.println(sdf.format(date));
Console exit: 10.07.2015 09:00
Assuming the time is correct, it's likely the fact that you're multiplying by 1,000. When creating the date the way you are, it takes in milliseconds. Is it possible that your input is already in milliseconds? (Your current method will be ~2 minutes off if so)
Date date=new Date(1436536800);
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String dateText = df2.format(date);
Date you are getting is a JSON string value. follow steps below to format it correctly.
First download Moment.js file and add it in your project.
var date1 = "1436536800"; // your long value contain in this variable.
var date2 = moment(date1).format(MMMM Do YYYY);//It will give you formatted date value.
see more formats below

Java convert unix timestamp to wrong time

I have unix timestammp stored in mysql. I am converting it into time. It displays wrong time.
Here is code:
Date date = new Date((long)timestamp*1000);
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
timeString = sdf.format(date);
System.out.println(timeString);`
timestamp is variable which contains unix timestamp.
Ex: for timestamp=1417437428505 it should show 6:07 PM and showing 12:31 AM
What is solution for it?
You're multiplying a timestamp which is already in milliseconds since the Unix epoch by 1000. You just want:
Date date = new Date(timestamp);
If you look at all of the date, not just the time, you'll see it's currently in 46886!
Are You sure that need multiplied by 1000? I tried pass without multiplying Date date = new Date(timestamp); and it printed 6:07 PM
Remove multiply with 1000 in
Date date = new Date((long)timestamp*1000);
than it works.

DateFormat not giving date in the desired format

I want to get the current date in the following format
yyyy_mm_dd
Am Using the below code
DateFormat date = new SimpleDateFormat("yyyy_mm_dd");
Date datetoday = new Date();
System.out.println(date.format(datetoday));
But its giving the result in this manner - 2013_56_25
However, it should give the result like 2013_03_25
Infact, the mm value varies every time I run it.
My system's date is of the format - 3/25/2013. (Idk if it has some relation with this)
What is the possible problem with this ?
Use upper case MM, lower case mm is for minutes.
DateFormat date = new SimpleDateFormat("yyyy_MM_dd");
Month is M, not m (which is minute)
Use MM instead of mm; lower case is for mintues; Uppercase for Months
You will have to use MM and not mm. Please refer the table from the image below
I got Different Result after parse the java.util.Date to java.sql.Date
String date="2012-05-02";
SimpleDateFormat df=new SimpleDateFormat("yyyy-mm-dd");
i got as a result is:2012-01-01
means 1 Day is less than actually required.

Categories

Resources