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())));
Related
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();
}
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.
Good day,
Disclaimer: I am very new to development.
I am developing an app and the user needs to enter a start time and end time. I then want to do a calculation to get the time taken. Below is the code I am using but it returns "an empty string".
dtiStartTime = new sap.m.DateTimeInput({
id : "StartTime", placeholder:"Select Start Time", type:"Time",width:"100px"
});
dtitotalTime = new sap.m.DateTimeInput({type:"Time",value:""});
dtiStopTime = new sap.m.DateTimeInput({
id : "StopTime", placeholder:"Select Stop Time", type:"Time",width:"100px",
change: [function(oEvent){totalTime.setValue(dtiStopTime.getValue() - dtiStartTime.getValue())}]
});
"getValue()" of DateTimeInput returns a javascript Date() object.
If you call "getTime()" of the Date object you get the time in milliseconds and can subtract them from each other. Afterwards you need to transform them into a value that you need (minutes/hours)...
var startDate = dtiStartTime.getValue();
var stopDate = dtiStopTime.getValue();
var differenceInMilliseconds = stopDate.getTime() - startDate.getTime();
Here is an example how to get the difference in seconds:
var start = this.byId('dateTimeStart').getDateValue();
var ende = this.byId('dateTimeEnde').getDateValue();
var diffInSeconds = (ende.getTime() - start.getTime())/1000;
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)));
}
}
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.