How covert C# DateTime to Java DateTimeusing Joda-Time - java

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

Related

How do I touch a folder with current time using set last modified date & time?

I'm trying to update the last modified date of a specific folder, here's what I've got:
public void touchFolder(){
File folderToTest = new File("C:\\Temp");
SimpleDateFormat dateFormatUtc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatUtc.setTimeZone(TimeZone.getTimeZone("UTC"));
String newTime = dateFormatUtc.format(new Date());
folderToTest.setLastModified(Long.parseLong(newTime));
}
I am just putting this code in a test case so don't worry about calling this method etc.
I'm getting errors with the parsing that date format as a long, what's the format used in setting the last modified date & time?
This is an example from the documentation, using java.nio.file.Files:
Path path = ...
FileTime now = FileTime.fromMillis(System.currentTimeMillis());
Files.setLastModifiedTime(path, now);
I think you should just do folderToTest.setLastModified(System.currentTimeMillis());
In your code newTime is a formatted date 2018-12-19 15:21:31 which can't be parsed to Long. What you want to do is supply the time in milliseconds e.g.:
Date d = new Date();
file.setLastModified(d.getTime());
As per File.setLastModified() method javadoc:
time - The new last-modified time, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)

Convert Date.toString() back to Date in Java [duplicate]

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

DateTime convertion in java

I have a date get saved in the database in IST format.
Date nowDate = new Date();
Date dateBefore = new Date(nowDate.getTime() - 7* 24 * 3600 * 1000);
System.out.println("Datebefore-->"+dateBefore);
Here in the above code dateBefore is get saved in the database.
From the database I am taking the data long value and I have to convert this into Google DateTime
Date dateBefore12 = new Date(longvalue);
com.google.api.client.util.DateTime dd = new DateTime(dateBefore12, TimeZone.getTimeZone("UTC"));
Now for example the output will be in the 2014-07-17T05:23:28.857Z which I have to pass to the Google You tube API.
Now from the response I will take Google DateTime, let say 2014-07-17T05:23:28.857Z which I have to increment the 1 minute and then convert it into long and save into db.
Convert the google DateTime to long.
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = dd.toString();
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
cal.add(Calendar.MINUTE,1);
Date time = cal.getTime();
long longvalue1 =cal.getTimeInMillis();
Now I will saved the data and try to retrieve it. It gives me back 2014-07-16T23:54:28.857Z.
But I need the save date value which I have increment by one minute in the format of google DateTime.
SimpleDateFormat also uses a time zone, due to an internal Calendar object, which defaults to the local time zone. If you don't want to use that default time zone, then before you call the format's parse() method, you should call setTimeZone() on it:
f.setTimeZone(utc);

Java not converting epoch correctly [duplicate]

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.

minus 1 hour to DateTime using Joda Time

I just want to subtract 1 hour from a DateTime I tried looking it up on Google and I found that there is a method called minus that takes a copy of the date and take a specific duration right here: http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#minus(long)
But I don't know how to use it and I can't an find a example on the internet.
Here's my code:
String string1 = (String) table_4.getValueAt(0, 1);
String string2= (String) table_4.getValueAt(0, 2);
DateTimeFormatter dtf = DateTimeFormat.forPattern("hh:mm a").withLocale(Locale.ENGLISH);
DateTime dateTime1 = dtf.parseDateTime(string1.toString());
DateTime dateTime2 = dtf.parseDateTime(string2.toString());
final String oldf = ("hh:mm a");
final String newf= ("hh.mm 0");
final String newf2= ("hh.mm a");
final String elapsedformat = ("hh.mm");
SimpleDateFormat format2 = new SimpleDateFormat(oldf);
SimpleDateFormat format2E = new SimpleDateFormat(newf);
Period timePeriod = new Period(dateTime1, dateTime2);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendHours().appendSuffix(".")
.appendMinutes().appendSuffix("")
.toFormatter();
String elapsed = formatter.print(timePeriod);
table_4.setValueAt(elapsed,0,3);
DecimalFormat df = new DecimalFormat("00.00");
System.out.println(dateTime1);
table_4.setValueAt("", 0, 4);
table_4.setValueAt("", 0, 5);
Sample Data:
dateTime1: 08:00 AM
dateTime2: 05:00 PM
the period will be 9 hours. but i want it to be 8 hrs only because i want to subtract the lunch break in my program.
i tried it with this stupid code:
dateTime1.minus(-1)
I also tried parsing string1 to double so I can subtract it by one.
double strindtoD = Integer.parseInt(string1);
I also tried making another DateTime and use period to get the difference of the two time
String stringOneHour = ("01:00 AM");
DateTime dateTime3 = dtf.parseDateTime(stringOneHour.toString());
Period timePeriod = new Period(dateTime3, dateTime1);
Just use:
dateTime.minusHours(1)
This is documented in the API.
Note that DateTime objects are immutable, so the operation alone has no effect. You need to assign the result of this method to a new object (or replace itself):
dateTime = dateTime.minusHours(1);
As to how to obtain a Period out of the difference between two DateTimes, you must first go through an Interval:
Period period = new Interval(begin, end).toPeriod();
Link to a SO post explaining why there is both Period and Interval.
Side note: Joda Time uses a LOT of indirections in its API; as such reading the Javadoc not only requires one to read the methods for one class, but also look at the list of inherited methods from all the inherited abstract classes/interfaces; for instance, a DateTime is also a ReadableInstant. One you get used to it, though, it's a breeze.
If you are using an older version of org.joda.time.DateTime then you can use minus(ReadablePeriod period) method like this
Date date = LocalDate.now().minus(new Period(1, 0, 0, 0)).toDate();
where Period accepts int hours, int minutes, int seconds, int millis parameters
By using Calender class object you can use this method to subtract hours.
cal.add(Calendar.HOUR_OF_DAY, -numberOfHours);
and also here is complete example link

Categories

Resources