Java 8 - SQL Timestamp to Instant with properly formatted time - java-8

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

Related

How to obtain first date of each month based on given year range in Nifi flow

I would like to know what could be the best way to obtain the starting date values for each month based on the date range.
For example: If I am given a year range of 2015-11-10 and 2018-01-15(format YYYY-mm-dd). Then I would like to extract following dates:
2015-12-01
2016-01-01
.
.
2018-01-01
You can try to use this flow for generating the first day of each month in the provided date range.
Overall flow
Step 1 Configuration: Start
Step 2 Configuration: Configure Date Range
Provide the start and end dates as configuration parameters via this step.
Step 3 Configuration: Generate First Dates For Months
This uses a Groovy script, which is provided below
Groovy script
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'yyyy-MM-dd';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("start_date"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("end_date"));
allFirstDates = "";
Calendar calendar = Calendar.getInstance();
Set firstDaysOfMonths = new LinkedHashSet();
for (int i = 0; i <= endDate-startDate; i++) {
calendar.setTime(startDate.plus(i));
calendar.set(Calendar.DAY_OF_MONTH, 1);
firstDayOfMonth = calendar.getTime();
if (firstDayOfMonth.compareTo(startDate) >= 0) {
firstDaysOfMonths.add(calendar.getTime().format(DATE_FORMAT));
}
}
firstDaysOfMonths.each {
firstDayOfMonth -> allFirstDates = allFirstDates + firstDayOfMonth + "\n";
}
flowFile = session.putAttribute(flowFile,"all_first_dates", allFirstDates );
session.transfer(flowFile,REL_SUCCESS)
Step 4 Configuration: View Result
Output of run:
When the flow is run, the attribute all_first_dates will be populated with the first dates of each month in the date range.

UTC to local method in DateTimeZone of Joda-Time to 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.

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

failed to manipulate my Arraylist

I need help , I have an arrayList of objects . This object contains multiple fields I'm interested in this question by two date fields (date_panne date_mise and running) and two other time fields (heure_panne and time start),
And I would like to obtain the sum of the difference between (date_panne, heure_panne) and (date_mise_en_marche; heure_mise_en_marche) to give the total time of failure.
if someone can help me please I will be gratful this is my function :
public String disponibile() throws Exception {
int nbreArrets = 0;
List<Intervention> allInterventions = interventionDAO.fetchAllIntervention();
List<Intervention> listInterventions = new ArrayList<Intervention>();
for (Intervention currentIntervention : allInterventions) {
if (currentIntervention.getId_machine() == this.intervention.getId_machine()
&& currentIntervention.getDate_panne().compareTo(getProductionStartDate()) >= 0
&& currentIntervention.getDate_panne().compareTo(getProductionEndDate()) <= 0) {
listInterventions.add(currentIntervention);
}
}
savedInterventionList = listInterventions;
return "successView" ;
}
Assuming the the dates are truncated to the day and are of type java.util.Date, and that the times only contain hours, minutes, seconds and milliseconds and are also of type Date, start by creating a method like
private Date combine(Date dateOnly, Date timeOnly) {
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(dateOnly);
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(timeOnly);
dateCalendar.add(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
dateCalendar.add(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
dateCalendar.add(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
dateCalendar.add(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND));
return dateCalendar.getTime();
}
Now, it's simply a matter of looping through the interventions you want to sum, computing the difference between the dates as milliseconds, and add them:
long totalMillis = 0L;
for (Intervention intervention : interventions) {
Date marche = combine(intervention.getDateMiseEnMarche(), intervention.getTimeMiseEnMarche());
Date panne = combine(intervention.getDatePanne(), intervention.getTimePanne());
long differenceInMillis = marche.getTime() - panne.getTime();
totalMillis += differenceInMillis;
}

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