UTC to local method in DateTimeZone of Joda-Time to Java 8 - java-8

We are changing Joda-Time API's to Java 8 time API's. In Joda-Time I have used:
DateTimeZone.convertLocalToUTC(this.getMillis(), true);
DateTimeZone.convertUTCToLocal(long millis);
Can any one tell me equivalent methods in Java 8?
Edited
convertLocalToUTC
DateTimeZone dateTimeZone = DateTimeZone.getDefault();
DateTime jodadatetime = new DateTime();
long utcTime = dateTimeZone.convertLocalToUTC(jodadatetime .getMillis(), true);
System.out.println(jodadatetime);
DateTimeZone dateTimeZone1 = DateTimeZone.UTC;
System.out.println(new DateTime(utcTime, dateTimeZone1));
Output
2017-08-09T17:27:57.508+05:30
2017-08-09T06:27:57.508Z
ConvertUtcToLocal
long utctolocal = dateTimeZone.convertUTCToLocal(jodadatetime.getMillis());
System.out.println("utc to local : " + new DateTime(utctolocal, dateTimeZone1));
Output
2017-08-09T17:27:57.508Z

So, your original date is 2017-08-09T17:27:57.508+05:30, then you want 2 things:
convertLocalToUTC: get 2017-08-09T06:27:57.508Z. This is a little bit tricky:
The original date is 2017-08-09T17:27:57.508+05:30, which is equivalent in UTC to 2017-08-09T11:57:57.508Z. What this method does is to convert this to the same local date and time but at the Calcutta timezone, and then you're printing it in UTC. In short:
original date is 2017-08-09T17:27:57.508+05:30
in UTC, that's the same as 2017-08-09T11:57:57.508Z
convertLocalToUTC converts this to 2017-08-09T11:57:57.508+05:30 (same date and time, but in Calcutta timezone)
and that's the same as 2017-08-09T06:27:57.508Z
To do this in Java 8, you can do:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
Instant i = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZoneSameInstant(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(i.toEpochMilli() + "=" + i);
Output:
1502260077508=2017-08-09T06:27:57.508Z
convertUTCToLocal: get 2017-08-09T17:27:57.508Z - the same date (2017-08-09) and time (17:27:57.508) but in UTC.
It's similar:
ZoneId zone = ZoneId.of("Asia/Calcutta");
// original date 2017-08-09T17:27:57.508+05:30
ZonedDateTime z = OffsetDateTime.parse("2017-08-09T17:27:57.508+05:30")
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZoneSameInstant(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(z.toInstant().toEpochMilli() + "=" + z);
Output:
1502299677508=2017-08-09T17:27:57.508Z
You can also get the dates from the millis value.
For case 1:
// millis for original joda date: jodadatetime.getMillis() (1502279877508 = 2017-08-09T17:27:57.508+05:30)
long millisFromJoda = 1502279877508L;
Instant instant = Instant.ofEpochMilli(millisFromJoda)
// convert to UTC (2017-08-09T11:57:57.508Z)
.atZone(ZoneOffset.UTC)
// convert to same local time in Calcutta
.withZoneSameLocal(zone)
// back to UTC
.toInstant();
System.out.println(instant.toEpochMilli() + "=" + instant);
Output:
1502260077508=2017-08-09T06:27:57.508Z
You can convert the Instant to another types if you want:
// convert to ZonedDateTime in UTC
ZonedDateTime zd = instant.atZone(ZoneOffset.UTC);
// convert to OffsetDateTime in UTC
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
Both will be 2017-08-09T06:27:57.508Z.
And for case 2:
ZonedDateTime zdt = Instant.ofEpochMilli(millisFromJoda)
// convert to a ZonedDateTime in Calcutta (2017-08-09T17:27:57.508+05:30[Asia/Calcutta])
.atZone(zone)
// convert to same local time in UTC
.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(zdt.toInstant().toEpochMilli() + "=" + zdt);
Output:
1502299677508=2017-08-09T17:27:57.508Z

Here is some code snippet that may help you get started:
LocalDateTime yourLocalTime = ...
long utc = yourLocalTime.toInstant(ZoneOffset.UTC).toEpochMilli();
or as you used strict = true the following:
long utc = ZonedDateTime.ofStrict(yourLocalTime, ZoneOffset.UTC, ZoneId.of("Z")).toInstant().toEpochMilli();
Converting back is similar:
LocalDateTime yourUtcTime = ...
long localTimeInMillis = yourUtcTime.toInstant(OffsetDateTime.now().getOffset() /* or: yourLocalTime.getOffset() */).toEpochMilli();
If you don't need the millis, but want to work with the DateTime-classes instead, you may want to use ZonedDateTime instead?
Creating a LocalDateTime from millis could be done as follows:
LocalDateTime yourLocalDateTime = Instant.ofEpochMilli(millisAsLong).atZone(/* your desired zone here */).toLocalDateTime();
where zone id could be ZoneId.of("Z"), ZoneId.systemDefault(), etc.

Related

How to convert Time in JMeter in 24 Hr format, while using shiftTime function to convert IST to UTC format?

Actually I'm trying to to shift the time, the application I'm working on is in UTC and I'm working in IST.
I've used both BEAN Shell pre processor and shiftTime function
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
int AddSeconds= 00; //this variable needs to be customized as per your need
int AddMinutes= 392; //this variable needs to be customized as per your need
int AddHours= 00; //this variable needs to be customized as per your need
Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.SECOND, AddSeconds);
c.add(Calendar.MINUTE, AddMinutes);
c.add(Calendar.HOUR, AddHours);
Date NewTime = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String mytime = df.format(NewTime);
vars.put("NewTime",mytime);
Shift Time :
"${__timeShift(yyyy-MM-dd'T'HH:mm:ss.SSS'Z',,PT393M,,)}"
Bun when I run the HTTP Request in Jmeter the time format is coming in 12Hrs only instead of 24 Hr
Also Time shift is taking in weird manner, I've tried all options from Stackoverflow from last 2 days and unable to achieve my task to convert IST to UTC.
This is what I'm using in Jmeter Post body
enter image description here
And this is what I'm getting as result
enter image description here
Time formats are getting totally mismatched here, can someone please help me to convert IST to UTC correctly while playing with these time formats and functions.
I don't think you can use __timeShift() function for getting the date in the different timezone, it will return you the current (default) one
So if you need to add 392 minutes to the current time in the time zone different from yours - you will have to go for __groovy() function and use TimeCategory class
Example code:
${__groovy(def now = new Date(); use(groovy.time.TimeCategory) { def nowPlusOneYear = now + 392.minute; return nowPlusOneYear.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"\,TimeZone.getTimeZone('IST')) },)}
Demo:
If you need to get the time in UTC just change IST to UTC
${__groovy(def now = new Date(); use(groovy.time.TimeCategory) { def nowPlusOneYear = now + 392.minute; return nowPlusOneYear.format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"\,TimeZone.getTimeZone('UTC')) },)}
More information: Creating and Testing Dates in JMeter - Learn How
Also be informed that since JMeter 3.1 you're supposed to be using JSR223 Test Elements and Groovy language for scripting
Just adding one more way to do this via bean shell preprocessor and it worked for me pretty well.
Here is the code to use... here -325 minutes is the difference between IST and UTC
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
int AddSeconds= 00; //this variable needs to be customized as per your need
int AddMinutes= -325; //this variable needs to be customized as per your need
int AddHours= 00; //this variable needs to be customized as per your need
Date now = new Date();
Calendar c = Calendar.getInstance();
c.setTime(now);
c.add(Calendar.SECOND, AddSeconds);
c.add(Calendar.MINUTE, AddMinutes);
c.add(Calendar.HOUR, AddHours);
Date NewTime = c.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String mytime = df.format(NewTime);
vars.put("NewTime",mytime);
// NewTime is your jmeter variable

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}

Put Time without Date in a Cell Jxl

I want to put the time on a cell. Here is the code I have so far:
DateFormat valueFormatDate = new DateFormat("HH:mm");
valueFormatDate.getDateFormat().setTimeZone( TimeZone.getTimeZone("Europe/Paris"));
WritableCellFormat formatDate = new WritableCellFormat(valueFormatDate);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
DateTime dt=new DateTime( 1, j+1,( java.util.Date )(formatter.parse(table.getValueAt(j, 1).toString())) ,formatDate); s.addCell(dt);
My Problem is, that the date is displayed too. How can I only display the time?
Try this, worked for me.
SimpleDateFormat fmt = new SimpleDateFormat("hh:mm:ss",new Locale("fr","FR"));
sheet.addCell(new Label(1,1, "Time: " + fmt.format(new Date())));

In windowsphone converting current time into millisecond

i have a time format like this:
string s = DateTime.Now.ToString();
which gives me output like
11/29/2013 6:26:13PM
Now how can i convert this output into millisecond in windowsPhone???
Updated:
First i want to save the current time when the user launch my app. after that whenever the user launch my app again then i also get the time and compare the current launching time with previously stored time and check whether the time difference becomes "one day" or not.
For this comparison i need to covert 11/29/2013 6:26:13PM this into millisecond.
Another question tell me how can i convert "6:26:13PM" only this into millisecond??
If I understood correctly just do this:
Create a date from your input:
DateTime yourInitialDateTime = DateTime.Parse("11/29/2013 6:26:13PM");
After that
TimeSpan span = DateTime.Now - yourInitialDateTime;
So in span.TotalDays you will have how many days has passed.
Edit
If you have only the time of day and want to know the millisecond of that time you must add a date and subtract it with hour 0:00:00 like this:
string dummyDate = "01/01/0001";
DateTime end = DateTime.Parse(dummyDate + " " + "6:26:13PM");
var milli = end.Subtract(new DateTime()).TotalMilliseconds;
That is it.
Try this.
var ThatDay = DateTime.Now.AddDays(-1); //This is hard coded but you have to get from where you are storing.
var Today = DateTime.Now;
var Diff = (Today - ThatDay).Milliseconds;
var FriendlyDiff = (Today - ThatDay).ToFriendlyDisplay(5);
public static class TimeSpanExtensions
{
private enum TimeSpanElement
{
Millisecond,
Second,
Minute,
Hour,
Day
}
public static string ToFriendlyDisplay(this TimeSpan timeSpan, int maxNrOfElements)
{
maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1);
var parts = new[]
{
Tuple.Create(TimeSpanElement.Day, timeSpan.Days),
Tuple.Create(TimeSpanElement.Hour, timeSpan.Hours),
Tuple.Create(TimeSpanElement.Minute, timeSpan.Minutes),
Tuple.Create(TimeSpanElement.Second, timeSpan.Seconds),
Tuple.Create(TimeSpanElement.Millisecond, timeSpan.Milliseconds)
}
.SkipWhile(i => i.Item2 <= 0)
.Take(maxNrOfElements);
return string.Join(", ", parts.Select(p => string.Format("{0} {1}{2}", p.Item2, p.Item1, p.Item2 > 1 ? "s" : string.Empty)));
}
}

Retrieving date format with am/pm in codeigniter

I have converted date to my local time as below:
$this->date_string = "%Y/%m/%d %h:%i:%s";
$timestamp = now();
$timezone = 'UP45';
$daylight_saving = TRUE;
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$this->updated_date = mdate($this->date_string,$time);
And I'm storing this field in to database.
Now at retrieval time I want format like this:
"11-04-2011 4:50:00 PM"
I have used this code:
$timestamp = strtotime($rs->updated_date);
$date1 = "%d-%m-%Y %h:%i:%s %a";
$updat1 = date($date1,$timestamp);
But this will give me only
"11-04-2011 4:50:00 AM"
But I have stored it like it was PM.
Might get voted down, but will have a go at it.
Is it because the MySQL stores it in 24 hour format? (assuming you are using the datetime field type)
Maybe this will help
Converting mysql TIME from 24 HR to AM/PM format
sorry if it doesn't.

Resources