Which piece of code is better? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am was writing some code, but I´m not sure which is better. In one way it's easier read what is happening, but I have more line of code.
In the other way, you has less line of code but I think is harder to understand.
String imp = importance.getSelectedItem().toString();
String title_str = title.getText().toString();
String body_str = body.getText().toString();
String location_str = location.getText().toString();
int day = date.getDayOfMonth();
int month = date.getMonth()+1;
int year = date.getYear();
int hh = time.getCurrentHour();
int mm = time.getCurrentMinute();
String date_str = year+"/"+month+"/"+day+" " + hh+":"+mm +":00"; // yyyy/MM/dd HH:mm:ss
long dateMilliseconds = new Timeconversion().timeConversion(date_str);
Conference conference = ConferenceBuilder.conference()
.id(idConf)
.importance(Double.parseDouble(imp))
.title(title_str)
.body(body_str)
.location(location_str)
.timeInMilliseconds(dateMilliseconds)
.build();
or
Conference conference2 = ConferenceBuilder.conference()
.id(idConf)
.importance(Double.parseDouble(importance.getSelectedItem().toString()))
.title(title.getText().toString())
.body(body.getText().toString())
.location(location.getText().toString())
// yyyy/MM/dd HH:mm:ss
.timeInMilliseconds(new Timeconversion().timeConversion(date.getYear()+"/"+date.getMonth()+1+"/"+date.getDayOfMonth()+" " + time.getCurrentHour()+":"+time.getCurrentMinute() +":00"))
.build();

Split the difference. I'd do something like this:
Conference conference2 = ConferenceBuilder.conference()
.id(idConf)
.importance(Double.parseDouble(importance.getSelectedItem().toString()))
.title(title.getText().toString())
.body(body.getText().toString())
.location(location.getText().toString())
// yyyy/MM/dd HH:mm:ss
.timeInMilliseconds(getTimeInMillis(datePicker, timePicker))
.build();
}
private long getTimeInMillis(DatePicker datePicker, TimePicker timePicker) {
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
return calendar.getTimeInMillis();
}
I don't think that extracting String objects from your textviews makes things any more readable, since your textviews are pretty clearly named.

Related

I have a date in int format DDMMYYYY, how can I separate day and month and year [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
int date1 = 22092021
int date2 = 03122021
I want to know which date is older
assuming each month has 30 days
As pointed out in comments, it's most likely that input might be coming as string. You can easily parse Date from string like this:
private static Date getDate(String dateStr) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyy");
return simpleDateFormat.parse(dateStr);
}
Then you can do something like this to check which date is older:
String date1 = "22092021";
String date2 = "03122021";
Date d1 = getDate(date1);
Date d2 = getDate(date2);
if (d1.compareTo(d2) < 0) {
System.out.println("d1 is older than d2");
} else if (d1.compareTo(d2) > 0) {
System.out.println("d2 is older than d1");
} else {
System.out.println("both are equal");
}
In case you're interested in extracting day, month and year from your Date instance, you can create a small utility method to convert it to Calendar like this:
private static Calendar toCalendar(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Then you can extract it with Calendar::get methods like this:
Calendar c1 = toCalendar(d1);
System.out.printf("%d %d %d\n", c1.get(Calendar.DAY_OF_MONTH), c1.get(Calendar.MONTH), c1.get(Calendar.YEAR));
Calendar c2 = toCalendar(d2);
System.out.printf("%d %d %d\n", c2.get(Calendar.DAY_OF_MONTH), c2.get(Calendar.MONTH), c2.get(Calendar.YEAR));
Apart from the obvious problems with this representation (see comments) the parts could be separated like this:
int y = date % 10000
date /= 10000
int m = date % 100
int d = date / 100

unix YYYYMMDDHHMMSS.miliseconds format to java date [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want date without time in java
unix format is
YYYYMMDDHHMMSS.miliseconds
unix string 20170817134131.384
string val = "20170817134131.384";
if (val != null) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
try {
date = df.parse(String.valueOf(val));
} catch (ParseException e) {
throw new RuntimeException("Failed to parse date: ", e);
}
return date;
}
Here's a simple solution to convert unix time to localDate and then you're free to format it as you please:
long time = 1491231860;
final LocalDate localDate = LocalDate.fromMillisSinceEpoch(unixSeconds);

How can I generate date object from string in format "23-Jan-2015" in java and javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need some help. I need to create a new date object in mm/dd/yyyy format from a string of format 24-Mar-2015.
You can use SimpleDateFormat.
String src = "24-Mar-2015";
Date date = new SimpleDateFormat("d-MMM-yyyy").parse(src);
String dst = new SimpleDateFormat("MM/dd/yyyy").format(date);
In JavaScript
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '/' + month + '/' + day;
}
alert(getFormattedDate(new Date(2015,3,24))); // 2015/03/24
The Date(String) constructor can be used to create date object from String, which can then be formatted by SimpleDateFormat.
String date = "24-Mar-2015";
System.out.println(new SimpleDateFormat("dd-MMM-yyyy").format(new Date(date)));
*To print month in full use SimpleDateFormat("dd-MMMM-yyyy") instead.
In JavaScript:
var myDate = new Date('2015/01/23');
myDate.toString(); // "Fri Jan 23 2015 00:00:00 GMT+0100 (CET)"

Convert 12 Hour to 24 Hour in JAVA within scope of UTC [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Please help me convert time from 12 hours to 24 hours format return time should be in UTC in JAVA
This will help you to convert time to 24 Hour
public static String convertTo24Hour(String Time) {
DateFormat f1 = new SimpleDateFormat("hh:mm a"); //11:00 pm
Date d = null;
try {
d = f1.parse(Time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat f2 = new SimpleDateFormat("HH:mm");
String x = f2.format(d); // "23:00"
return x;
}
Later on you may convert to UTC as per your wish or you may compile code in one function
public static String CalculateUTC_Time(String Date, String Time) {
String X[] = Time.split(":");
int Hours = Integer.parseInt(X[0]);
int Minutes = Integer.parseInt(X[1]);
LocalDate date = new LocalDate(Date);
LocalTime time = new LocalTime(Hours, Minutes);
DateTime dt = date.toDateTime(time);
SimpleDateFormat f2 = new SimpleDateFormat("HH:mm");
f2.setTimeZone(TimeZone.getTimeZone("UTC"));
return (f2.format(dt.toDate()));
}

Let Android find Date and calculate the days between this and now [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm really new in this area.
But I want to find out e.g. the first sunday in July 2013 and then Android should calculate the days between now and then.
Thank you so much for helping!
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
Here's an approximation...
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
If you are going to some advanced calculations on dates in Java, I recommend Joda library (http://joda-time.sourceforge.net).
Using this library to solve your problem, it could be done like this:
LocalDate firstSundayOfJuly = new LocalDate(2013, 7, 1);
firstSundayOfJuly = firstSundayOfJuly.dayOfWeek().withMaximumValue();
Interval i = new Interval(LocalDate.now().toDateTimeAtStartOfDay(),
firstSundayOfJuly.toDateTimeAtStartOfDay());
System.out.println("days = " + i.toDuration().getStandardDays());

Categories