This is what I did, but it did not take into account the leap years
public static int calculateAge(String yyyyMMddBirthDate){
DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd");
Date birthDateDate = fmt.parse(yyyyMMddBirthDate);
Date nowDate=new Date();
long differenceInMillis=nowDate.getTime()-birthDateDate.getTime();
int days=(int)Math.abs(differenceInMillis/(1000*60*60*24));
int ages=(int)days/365;
System.out.println(days+" days");
return ages;
}
I heard we have to use Joda time to calculate ages, but seem GWT does not support Joda time.
Can we just simply use simple code to calculate ages in GWT rather than using library?
Note: This is GWT question, not Java one. The GWT does not support java.text or Joda.
This should work (even for GWT), at least for births that are after about 1582:
// currentDate and birthDate are in the format yyyyMMdd
final int age = (Integer.valueOf(currentDate) - Integer.valueOf(birthDate)) / 10000;
You've already calculated the age in milliseconds, but you need to convert it to the highly arbitrary Western "years."
Best to use a library like JodaTime or Calendar that have these edge cases programmed in. Luckily people have ported it to GWT.
See: Date time library for gwt
Update: It really depends on what answer you want. Generally, comparing the current year to the birth year would get you the correct answer. So, if you want integer years lived so far:
Date dateBirth = ...;
Date dateNow = new Date();
int yearsOld = dateNow.getYear() - dateBirth.getYear();
To account for the fractional year, you'll need to test for leap days (if you want day precision) or leap seconds (if you want leap second precision). So, again, it depends what result you seek, which you've not said.
Regardless, this has nothing to do with GWT and everything to do with the basics of date/time math. either you'll have to bring it in via a library, or do it yourself. I'd suggest a library, since the calculations are elaborate. Just look inside the BaseCalendar that Java uses.
I ran into this today and here's what I came up with. This models how I would mentally calculate someone's age given a date of birth.
(using com.google.gwt.i18n.shared.DateTimeFormat)
private int getAge(Date birthDate) {
int birthYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(birthDate));
int birthMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(birthDate));
int birthDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(birthDate));
Date today = new Date();
int todayYear = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(today));
int todayMonth = Integer.parseInt(DateTimeFormat.getFormat("MM").format(today));
int todayDayOfMonth = Integer.parseInt(DateTimeFormat.getFormat("dd").format(today));
boolean hasHadBirthdayThisYear;
if (todayMonth < birthMonth) {
hasHadBirthdayThisYear = false;
} else if (todayMonth > birthMonth) {
hasHadBirthdayThisYear = true;
} else {
hasHadBirthdayThisYear = birthDayOfMonth <= todayDayOfMonth;
}
int age = todayYear - birthYear;
if (!hasHadBirthdayThisYear) {
age--;
}
return age;
}
import java.util.*;
public class Practice2 {
public static int calculateAge(String yyyyMMddBirthDate) {
// check the input ?
int birthYear = Integer.parseInt(yyyyMMddBirthDate.substring(0,4));
Date nowDate = new Date();
int nowYear = nowDate.getYear() + 1900;
//rough age and check whether need -- below
int roughAge = nowYear - birthYear;
int birthMonth = Integer.parseInt(yyyyMMddBirthDate.substring(5,7));
int birthDay = Integer.parseInt(yyyyMMddBirthDate.substring(8,10));
//1970-01-01T 00:00:00
long now = nowDate.getTime();
long days = now / (3600l * 1000l * 24l);
int daySum = 0;
for( int i = 1970; i < nowYear; i ++ ){
daySum = daySum + yearDays(i);
}
int[] monthDays = {31, 28 , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
monthDays[1] = yearDays(nowYear) - 337;
for( int i = 0; i < birthMonth -1; i ++ ){
daySum = daySum + monthDays[i];
}
daySum = daySum + birthDay;
if( daySum > days ){
roughAge--;
}
return roughAge;
}
private static int yearDays(int year) {
if( ( (year%100==0)&&(year%400==0) )
||((year%100!=0)&&(year%4==0))){
return 366;
}
return 365;
}
public static void main(String[] args) {
System.out.println(calculateAge("1990-12-30"));
}
}
Related
So this is what my calender is supposed to look like;
I'm thinking of making a listView of days, but how do I make it linked to an actual calender so I get the correct days/dates ?
Create the current week from any date using weekday something like this:
void main() {
final any = DateTime.now().add(Duration(days: 2));
final dateOnly = DateTime(any.year, any.month, any.day);
final week = [
for (var i = 1; i <= 7; i++)
dateOnly.subtract(Duration(days: dateOnly.weekday - i))
];
}
I'm trying to make a class. Part of the class is to calculate the shipping costs to an order. If the order the order is $0 - $50.00 then the shipping charge is 8% of the subtotal cost of the order. Else if the order is over $50.00 shipping is free. So I coded this so far, but I'm getting the error:
public class Order
{
private double salesTaxRate;
private double subTotal;
private double shipCost;
private double salesTax;
private double total;
//Constructor to set sales tax rate
public Order( double taxRate)
{
salesTaxRate = taxRate;
subTotal = 0;
shipCost = 0;
salesTax = 0;
total = 0;
}//End constructor
public int setCost(double subTotal)
{
if(subTotal == 0 || subTotal <= 50.00)
{
shipCost = subTotal * 0.08;
return shipCost;
}
else
{
shipCost = 0;
return shipCost;
}
}//End setCost method
I know what the error is, I just don't understand why I'm getting it. I am still new to programming so I ask for your patience. But any help would be appreciated.
I'm trying to store the time in milliseconds for every time this time park is executed. And then I would like to use HdrHistogram to represent the latency.
However, i can't store the times in my array. Please, could you provide any help?
public class PracticeLatency1
{
public static void main(String [] args)
{
int[] startTimes;
long startTime;
int index=0;
startTimes = new int[10000];
startTime = System.currentTimeMillis();
runCalculations();
startTimes[index++] = (int) (System.currentTimeMillis() - startTime);
System.out.println(startTimes);
}
/**
* Run the practice calculations
*/
// System.currentTimeMillis()
private static void runCalculations()
{
// Create a random park time simulator
BaseSyncOpSimulator syncOpSimulator = new SyncOpSimulRndPark(TimeUnit.NANOSECONDS.toNanos(100),
TimeUnit.MICROSECONDS.toNanos(100));
// Execute the operation lot of times
for(int i = 0; i < 10000; i++)
{
syncOpSimulator.executeOp();
}
// TODO Show the percentile distribution of the latency calculation of each executeOp call
}
}
I'm learning Dart & flutter for 2 days and I'm confused about how to convert seconds (for example 1500sec) to minutes.
For studying the new language, I'm making Pomodoro timer, and for test purposes, I want to convert seconds to MM: SS format. So far, I got this code below, but I'm stuck for a couple of hours now... I googled it but could not solve this problem, so I used Stackoverflow. How should I fix the code?
int timeLeftInSec = 1500;
void startOrStop() {
timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (timeLeftInSec > 0) {
timeLeftInSec--;
timeLeft = Duration(minutes: ???, seconds: ???)
} else {
timer.cancel();
}
}
}
}
This code works for me
formatedTime({required int timeInSecond}) {
int sec = time % 60;
int min = (time / 60).floor();
String minute = min.toString().length <= 1 ? "0$min" : "$min";
String second = sec.toString().length <= 1 ? "0$sec" : "$sec";
return "$minute : $second";
}
now just call the function
formatedTime(timeInSecond: 152)
formated time example
Without formatting:
int mins = Duration(seconds: 120).inMinutes; // 2 mins
Formatting:
String formatTime(int seconds) {
return '${(Duration(seconds: seconds))}'.split('.')[0].padLeft(8, '0');
}
void main() {
String time = formatTime(3700); // 01:01:11
}
You can try this :
int minutes = (seconds / 60).truncate();
String minutesStr = (minutes % 60).toString().padLeft(2, '0');
This is the way I've achieved desired format of MM:SS
Duration(seconds: _secondsLeft--).toString().substring(2, 7);
Here is an example of what toString method returns:
d = Duration(days: 0, hours: 1, minutes: 10, microseconds: 500);
d.toString(); // "1:10:00.000500"
So with the substring method chained you can easily achive more formats e.g. HH:MM:SS etc.
Check out this piece of code for a count down timer with formatted output
import 'dart:async';
void main(){
late Timer timer;
int startSeconds = 120; //time limit
String timeToShow = "";
timer = Timer.periodic(Duration(seconds:1 ),(time){
startSeconds = startSeconds-1;
if(startSeconds ==0){
timer.cancel();
}
int minutes = (startSeconds/60).toInt();
int seconds = (startSeconds%60);
timeToShow = minutes.toString().padLeft(2,"0")+"."+seconds.toString().padLeft(2,"0");
print(timeToShow);
});
}
/*output
01.59
01.58
01.57
...
...
...
00.02
00.01
00.00*/
static int timePassedFromNow(String? dateTo) {
if (dateTo != null) {
DateTime targetDateTime = DateTime.parse(dateTo);
DateTime dateTimeNow = DateTime.now();
if (targetDateTime.isAfter(dateTimeNow)) {
Duration differenceInMinutes = dateTimeNow.difference(targetDateTime);
return differenceInMinutes.inSeconds;
}
}
return 0;
}
static String timeLeft(int seconds) {
int diff = seconds;
int days = diff ~/ (24 * 60 * 60);
diff -= days * (24 * 60 * 60);
int hours = diff ~/ (60 * 60);
diff -= hours * (60 * 60);
int minutes = diff ~/ (60);
diff -= minutes * (60);
String result = "${twoDigitNumber(days)}:${twoDigitNumber(hours)}:${twoDigitNumber(minutes)}";
return result;
}
static String twoDigitNumber(int? dateTimeNumber) {
if (dateTimeNumber == null) return "0";
return (dateTimeNumber < 9 ? "0$dateTimeNumber" : dateTimeNumber).toString();
}
I am using Quartz.NET library and I need to execute a job every two days and repeat it every two hours between 22 PM and 6 AM. I don't know how to achieve this. I tried all of triggers combining them with calendars to exclude other hours, but nothing works as I want. Any idea?
This is the answer.
protected void Application_Start()
{
//....
EveryTwoWeek();
//....
}
private void MainJob()
{
int hourNumber = 2;
var schedFact = new Quartz.Impl.StdSchedulerFactory();
var sched = schedFact.GetScheduler();
sched.Start();
var twoHourlyTriggerFrom22To6 = Quartz.TriggerUtils.MakeHourlyTrigger(hourNumber);
twoHourlyTriggerFrom22To6.StartTimeUtc = System.DateTime.Now.Date.AddHours(22);
twoHourlyTriggerFrom22To6.EndTimeUtc = System.DateTime.Now.Date.AddHours(22 + 8);
var jobDetail = new Quartz.JobDetail("Method", methodType);
sched.ScheduleJob(jobDetail, twoHourlyTriggerFrom22To6);
}
private void EveryTwoDays()
{
int dayNumber = 2;
var schedFact = new Quartz.Impl.StdSchedulerFactory();
var sched = schedFact.GetScheduler();
sched.Start();
var everyTwoDaysTrigger = Quartz.TriggerUtils.MakeImmediateTrigger(int.MaxValue, new System.TimeSpan(0, dayNumber * 24, 0, 0));
everyTwoDaysTrigger.StartTimeUtc = System.DateTime.Now.Date;
var jobDetail = new Quartz.JobDetail("MainJob", mainJobType);
sched.ScheduleJob(jobDetail, everyTwoDaysTrigger);
}
What about 0 0 0,2,4,6,22 1/2 * ? *
Strictly speaking, this isn't every two days, but on the 1st, 3rd, 5th etc of each month.