I am trying to convert pure java code into swift.But,I am having a little problem with setting the current time.I can get the current time in milliseconds.But I cant set the current time.Any help with that?
Here is my code
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
let now = NSDate()
var auctionDate = [String:String]()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
var sdfDDMMYYYYEEE : NSDateFormatter!
sdfDDMMYYYYEEE.dateFormat = "dd/MM/yyyy (EEE)"
var sdfDDMMYYYY : NSDateFormatter!
sdfDDMMYYYY.dateFormat = "dd/MM/yyyy"
var sdfEEE : NSDateFormatter!
sdfEEE.dateFormat = "EEE"
// This is how i get the current time
println((now.timeIntervalSince1970)*1000 + 86400000.00)
for var i = 0; i < 5; i++ {
if sdfEEE.stringFromDate(now) == "Sun" {
// This is where i have to set my time with that ((now.timeIntervalSince1970)*1000 + 86400000.00)
i--;
continue;
}
auctionDate[(sdfDDMMYYYY.stringFromDate(now) as String)] = (sdfDDMMYYYYEEE.stringFromDate(now) as String)
// Here too I have to set my time
}
println(dateFormatter.stringFromDate(now))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is the java code that I want to convert into swift code
import java.text.*;
import java.util.*;
public class DateTest{
Date now = new Date();
Map<String, String> myDate = new LinkedHashMap<String, String>();
myDate.put("", "All");
SimpleDateFormat sdfDDMMYYYYEEE = new SimpleDateFormat("dd/MM/yyyy (EEE)");
SimpleDateFormat sdfDDMMYYYY = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdfEEE = new SimpleDateFormat("EEE");
for (int i = 0; i < 5; i++) {
if (sdfEEE.format(now).equals("Sun")) {
now.setTime(now.getTime() + 86400000);
i--;
continue;
}
myDate.put(sdfDDMMYYYY.format(now), sdfDDMMYYYYEEE.format(now));
now.setTime(now.getTime() + 86400000);
}
}
Any help with setting the current time in swift.I am almost closing to my answer.
In your code you want to add seconds to time eince 1970. You're in luck, there is an initializer for that: NSDate(timeIntervalSince1970: NSTimeInterval)
let now = NSDate(timeIntervalSince1970: 86400000)
This will create a new NSDate and add 86400000 seconds to the time in seconds right now since 1970.
Related
It wont get the minutes. i need to return minutes.
How to return sum of minutes while iterating over Localtime in Java?
public String userLunchHoursSum(String username) {
List<WorkHour> workHours = workHourRepository.findWorkHoursByUsername(username);
System.out.println(Arrays.toString(workHours.toArray()));
long diff = 0;
LocalTime lunchTime;
long minutes = 0;
LocalTime plusMinutes = null;
for (WorkHour workHour : workHours) {
lunchTime = workHour.getLunch_time().toLocalTime(); //00:30:00
plusMinutes = lunchTime.plusMinutes(lunchTime.getMinute());
}
if(workHours.size()!= 0) {
return Long.toString(plusMinutes.getMinute());
}
return "00:00";
}
getLunch_time returns java.sql.Time.
As mentioned, you should be storing duration instead of localtime. If this is something you have no control over, consider migrating the database or creating a intermediate parsing function. Example code that I have not run, because I don't know what is in WorkHour.
// leave the string formatting to other functions
public long userLunchHoursSum(String username) {
List<WorkHour> workHours = workHourRepository.findWorkHoursByUsername(username);
Duration totalDuration = Duration.ZERO;
for (WorkHour workHour : workHours) {
// save your time in the appropriate format beforehand
// do not use local time to store duration.
Duration lunchTime = Duration.between(LocalTime.MIDNIGHT, workHour.getLunch_time().toLocalTime()); //00:30:00
totalDuration = totalDuration.plus(lunchTime);
}
return totalDuration.toMinutes();
}
I have a scenario where i want to select the nearest date or the past date from a bunch of data which i am getting from a ajax call.
For example: If I am getting three rows with three different date like 12/12/2018, 12/3/2018 and 1/1/2018 then I want to return 1/1/2018.
And also if the array doesn't contains past date then it should return the nearest date to the current date.
Please suggest me something to achieve this.
Maybe a function like this would be useful:
function getNearestDate(dates, date) {
if (!dates || dates.length == 0) {
return null;
}
if (!date) {
date = new Date();
}
var result = dates[0];
var dt = Math.abs(new Date(dates[0])-date);
var minimum = dt;
for (var i=1;i<dates.length;i++) {
dt = Math.abs(new Date(dates[i])-date);
if (dt < minimum) {
result = dates[i];
minimum = dt;
}
}
return result;
}
I am getting exception while invoking NotesCalendar.getNewInvitations method.
NotesException: NotesCalendar error: The database handle is NULL
at lotus.domino.local.NotesCalendar.NgetNewInvitations(Native Method)
at lotus.domino.local.NotesCalendar.getNewInvitations(Unknown Source)
at JavaAgent.main(Unknown Source)
I am trying to run this code locally to Domino Server.
import lotus.domino.*;
public class JavaAgent extends NotesThread {
public static void main(String []args){
try
{
NotesThread.sinitThread(); // start thread
Session session = NotesFactory.createSession();
System.out.println("session="+session);
// (Your code goes here)
DbDirectory dbdir = session.getDbDirectory("");
System.out.println("dbdir="+dbdir);
Database db1= session.getDatabase("server", "Conf");
NotesCalendar cal = session.getCalendar(db1);
java.util.Calendar jdt = java.util.Calendar.getInstance();
jdt.set(2015, 1, 1, 1, 1, 1);
DateTime dt1 = session.createDateTime(jdt);
DateTime dt2 = session.createDateTime("Yesterday 02");
// java.util.Vector invites = cal.getNewInvitations(dt1, dt2);
// System.out.println("invites "+invites.size());
java.util.Vector invites= cal.getEntries(dt1, dt2);
for (int j = 0; j < 3; j++) {
// Create document to post results
Document doc = db1.createDocument();
doc.appendItemValue("Form", "main");
doc.appendItemValue("subject", "New invitations");
RichTextItem body = doc.createRichTextItem("body");
if (invites.size() == 0) body.appendText("No invitations");
else {
for (int i = 0; i < invites.size(); i++) {
NotesCalendarNotice cale = (NotesCalendarNotice)invites.elementAt(i);
body.appendText(cale.read());
cale.recycle();
body.addNewLine();
}
}
doc.save(true, true);
java.util.concurrent.TimeUnit.MINUTES.sleep(30);
invites = cal.getNewInvitations(dt1, cal.getUntilTime());
} }
catch(Exception e)
{
e.printStackTrace();
}
finally
{
NotesThread.stermThread(); // must terminate every thread
}
}
}
The simple answer is getNewInvitations() doesn't make sense in the context of a resource reservation database. The method was designed to read unprocessed invitations from a mail file.
However, in the comments you say your code doesn't work for mail files either. It might be helpful to get something simpler to work and then build on that. I just tried the following code:
database = session.getDatabase(null, "mail/user.nsf");
NotesCalendar calendar = session.getCalendar(database);
// Start date is 01-Jan-2015
java.util.Calendar start = java.util.Calendar.getInstance();
start.set(2015, 0, 1);
dtStart = session.createDateTime(start);
// End date is now
java.util.Calendar end = java.util.Calendar.getInstance();
dtEnd = session.createDateTime(end);
// Get entries on the calendar between start and end
Vector<?> entries = calendar.getEntries(dtStart, dtEnd);
System.out.println("Number of entries is " + entries.size());
// Get invitations from start date (from the Inbox)
Vector<?> invites = calendar.getNewInvitations(dtStart, calendar.getUntilTime());
System.out.println("Number of invites is " + invites.size());
Everything worked as expected. Perhaps you could try the above code and see if getNewInvitations() still throws an exception.
I am trying to sum durations in the following format: "hh:mm:ss" (e.g.: "08:55:12") using Joda Time:
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2).appendHours()
.appendLiteral(":").printZeroAlways().printZeroAlways()
.minimumPrintedDigits(2).appendMinutes().appendLiteral(":")
.printZeroAlways().minimumPrintedDigits(2).appendSeconds()
.toFormatter();
Duration totalTime = Duration.ZERO;
for (Entry entry : entries) {
Period period = formatter.parsePeriod(entry.getTime());
Duration duration = period.toStandardDuration();
totalTime = totalTime.plus(duration);
}
Period totalPeriod = totalTime.toPeriod();
if (totalPeriod.getHours() < 10) {
hours = "0" + totalPeriod.getHours();
} else {
hours = Integer.toString(totalPeriod.getHours());
}
mTextView.setTextView(hours
+ String.format("%02d:%02d", totalPeriod.getMinutes(),
totalPeriod.getSeconds()));
For some reason, it is giving me wrong results (summed durations is way too long). Can you help me find the cause of this problem?
I think you have just forgotten a colon between hour-part and minute part causing the total sum looking like 2701:44 instead of 27:01:44 (this is an example for the sum of the three elements "03:20:45", "00:40:11", "23:00:48" which is correctly calculated by Joda-Time).
So your solution should finally look like:
String output =
hours + String.format(":%02d:%02d", totalPeriod.getMinutes(), totalPeriod.getSeconds());
System.out.println(output); // 27:01:44
But easier is just to reuse your formatter object for printing:
System.out.println(formatter.print(totalPeriod)); // 27:01:44
If you are interested in a pattern-based solution then check out my library Time4J with this example:
// input
String[] periods = { "03:20:45", "00:40:11", "23:00:48" };
// initialization
Duration.Formatter<ClockUnit> timeFormat =
Duration.Formatter.ofPattern(ClockUnit.class, "hh:mm:ss");
Duration<ClockUnit> dur = Duration.ofZero();
// calculate the sum
for (String entry : periods) {
dur = dur.plus(timeFormat.parse(entry));
}
dur = dur.with(Duration.STD_CLOCK_PERIOD); // normalization
System.out.println(timeFormat.format(dur)); // 27:01:44
i m using jfreechart to draw a graph about a logger of operations in a computer.
ex:
1:2012/09/39/28 06:55:37 8 S 0x1c0c762 Terminal --geometry=134x35 --display :0.0 --role=Terminal-0x10591b0-16869-1343137248 --show-menubar --show-borders --hide-toolbars --working-directory /home/termier "Terminal", "Terminal" "Terminal - termier#akagi: ~"
2:2012/09/39/28 06:55:41 8 S 0x1600313 /usr/lib/xfce4/notifyd/xfce4-notifyd "xfce4-notifyd", "Xfce4-notifyd" "xfce4-notifyd"
for now , i can draw every point just like (2012/09/39/28 06:55:37,Terminal),scilicet: x-axis is 2012/09/39/28 06:55:37 , Y-axis is: Terminal (i use 1 to present Terminal ,as for other commands just like Terminal... 2:/usr/lib/xfce4/notifyd/xfce4-notifyd ,etc...)
but what i need is draw a block ,like:
terminal 1: _________S||||||
/usr/lib/xfce4/notifyd/xfce4-notifyd2:______________S||||||
com 3: _____S|||||
(S:start ,eg: 2000/12/12 09:22:10 start)
.....
(when the first command end, another one will be start ,i just can get the start, it means that the post command is the end time of the previous command)
but not: 1: S
2: S
3: S
here some codes to you.
private XYDataset createDataset() {
Calendar precal;
Calendar postcal;
this.flags = modelfocus.getListflag();
commands = modelfocus.getListCommand();
DateFormat formatedate = new SimpleDateFormat("yyyy/MM/ww/dd HH:mm:ss");
precal = Calendar.getInstance();
postcal = Calendar.getInstance();
for (int i = 0; i < countCom; i++) {
this.series[i] = new TimeSeries(commands.get(i));
}
for (Focus listTxt : modelfocus.getList()) {
try {
Date d = new Date();
d = formatedate.parse(listTxt.date2String());
System.out.println(d);
precal.setTime(d);
//postcal.setTime();
} catch (ParseException e) {
System.out.println("Can't change this date");
e.printStackTrace();
}
String eachCmd = listTxt.getCommand();
for (int i = 0; i < countCom; i++) {
if (eachCmd == commands.get(i)) {
series[i].addOrUpdate(new Second(precal.getTime()),
flags.get(i));
}
}
}
TimeSeriesCollection dataset = new TimeSeriesCollection();
for (int i = 0; i < countCom; i++) {
dataset.addSeries(this.series[i]);
}
return dataset;
}
Please can someone give help to solve this problem, thank you very much.
As shown in this example, you can change the Shape used to render the values of a time series. A Rectangle is shown below.
r.setSeriesShape(0, new Rectangle(-4, -4, 9, 9));