This question already has answers here:
How can I convert epoch time to date and time in Java?
(2 answers)
Closed 1 year ago.
I'm trying to convert the following epoch time
1382364283
When plugging this into an online converter it gives me the correct results.
10/21/2013 15:00:28
But the following code
Long sTime = someTime/1000;
int test = sTime.intValue(); // Doing this to remove the decimal
Date date = new Date(test);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formatted = format.format(date);
this.doorTime = formatted;
Returns
16/01/1970 17:59:24
I've tried several other ways to convert this, is there something I'm missing?
An epoch time is a count of seconds since epoch. You are dividing it by one thousand, gettings the number of thousands of seconds, that is, kiloseconds. But the parameter that Date takes is in milliseconds. Your code should be:
long someTime = 1382364283;
long sTime = someTime*1000; // multiply by 1000, not divide
Date date = new Date(sTime);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formatted = format.format(date);
System.out.println(formatted); // 21/10/2013 10:04:43
I don't get exactly your result, but I get the same results as online converters I tried.
The constructor Date(long time) takes a time in millis ! As you divide your someTime (which is probably in millis) by 1000, you get time in seconds instead of millis.
Related
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.
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
I am new to Joda and need help. I am trying to convert this C# code to java. I have been doing some research on Joda-time as well as looking at the documentation for the library. I am trying to get the difference epoch and UTC now(). but not sure how to achieve this using Joda's Interval class. Here is the C# method getting epoch and checking it against UTC now(). Then getting the difference between the two dates.
public static void AddApiAuthenticationHeaders(this HttpClient httpClient, HttpMethod httpMethod, string publicKey, string privateKey)
{
httpClient.DefaultRequestHeaders.Add("X-PSK", "thisisatestpublickey");//key:K-PSK
DateTime epochStart = new DateTime(1970,01,01,0,0,0,0, DateTimeKind.Utc); //Getting UTC DATE since epoch
TimeSpan ts = DateTime.UtcNow - epochStart; //get the current timestamp between now and january 1970
string stamp = Convert.ToUInt64(ts.TotalSeconds).ToString(); //get the total seconds that have elasped
httpClient.DefaultRequestHeaders.Add("X-Stamp", stamp);
//research extension method
string[] data = new string[] {publicKey, stamp.ToString(), httpMethod.Method };
byte[] expectedSignature = data.ComputeHash(privateKey);
httpClient.DefaultRequestHeaders.Add(HttpRequestMessageExtensions.SignatureHeaderName, Convert.ToBase64String(expectedSignature));
}
This works fine but now I want to do the same thing in java using Joda.
This is what I have been trying to do but am I am to understand how to get the difference in the two time using the Interval class.
DateTime epochStart = new DateTime(1970,1,1,0,0,0,0, DateTimeZone.UTC);
Interval ts = new Interval(DateTime.now(DateTimeZone.UTC).getMillis(), epochStart.getMillis());
String stamp = ts.toString(); // I know here is not right
I'm not really a C# expert, but this block of code:
DateTime epochStart = new DateTime(1970,01,01,0,0,0,0, DateTimeKind.Utc); //Getting UTC DATE since epoch
TimeSpan ts = DateTime.UtcNow - epochStart; //get the current timestamp between now and january 1970
string stamp = Convert.ToUInt64(ts.TotalSeconds).ToString(); //get the total seconds that have elasped
Appears to just get the number of seconds since the epoch and convert it to a string. So here is the equivalent Java code:
String stamp = String.valueOf(System.currentTimeMillis() / 1000);
This question already has answers here:
How to add 10 minutes to my (String) time?
(8 answers)
How can I read and parse a date and time in Android?
(2 answers)
Closed 7 years ago.
I am calling an API and as per the guidelines calling it every time is inefficient as the data does not change that regularly. They recommend calling it once and then not polling until 10 minutes has passed.
I am calling this from an Android app and so I want to store the current date plus 10 minutes. I do this like so:
Date forecastRefreshDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(forecastRefreshDate);
cal.add(Calendar.MINUTE, 10);
editor.putString("ForecastRefreshDate", forecastRefreshDate.toString());
editor.apply();
So now when this code is run again it needs to check if the current time (new Date()) is > the value saved in the cache/app file.
How do I create a Date variable equal to the value stored in the cache as a String?
Convert date to epoch time, which is a number of milliseconds stored as a long. Store long as string and parse back into long when needed.
long epoch = date.getTime(); //where date is your Date
String yourString = Long.toString(epoch); //to string for storage
long time = Long.valueOf(yourString).longValue(); ; //back to epoch
Date originaldate = new Date(Long.parseLong(time)); //back to date
When dealing with time, which is needed only internally to measure time periods,
It is much better to store timestamps as long value (millis sicne 1.1.1970 UTC).
Use long timestamp = System.currentTimeMillis()
If a String storage is neccesary simply convert the Long to a String.
String timeStampStr = String.parseLong(timeStamp);
Do not use Date.toString for other things than for logging or debugging.
The toString() representation may be different in other countries.
If a human readable timestamp string is needed you have to specify a Specific DateFormat, see also DateFormatter.
Parsing a long it the most efficent way, however there may be cases that you have already formatted a date to some other format and want to parse that. Then you should use this
private static final String format = "yyyy-MM-dd HH:mm:ss";
private static final SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.ENGLISH);
private Calendar dateTime = Calendar.getInstance();
public void setDateTime(String dateTimeString) {
try {
dateTime.setTime(formatter.parse(dateTimeString));
} catch (ParseException e) {
// Dummy handled exception
dateTime.setTimeInMillis(0);
}
}
Parse a long containing milliseconds since epoch
Date date = new Date(Long.parseLong(timeInMillisecondsString));
Since you're using a plain toString() it should be coverable using a SimpleDateFormat.
Try this:
DateFormat dateFormat = new SimpleDateFormat();
Date myDate = dateFormat.parse(myDateString);
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.