datetime - Simple Age Calculator base on date of birth in C# -
datetime - Simple Age Calculator base on date of birth in C# -
this question has reply here:
how calculate someone's age in c#? 54 answersi have created simple age calculator. want remove decimal places problem when substract now
bday
.
example : input 2012
, 10
, 23
, date 2014-10-22
, when 2014.1022 - 2012.1023
result 1.9999...
want remove decimal places , remain whole number 1
, time utilize string.format("{0:00}"
rounds off result 02
even when utilize converttoint32
, don't want utilize split string needs lot of code.
any ideas?
static void main(string[] args) { string year, month, day = string.empty; console.writeline("enter birthdate:"); console.writeline("year :"); year = console.readline(); console.writeline("month :"); month = console.readline(); console.writeline("day :" ); day = console.readline(); seek { datetime date = convert.todatetime(year + "-" + month + "-" + day); var bday = float.parse(date.tostring("yyyy.mmdd")); var = float.parse(datetime.now.tostring("yyyy.mmdd")); if (now < bday) { console.writeline("invalid input of date"); console.readline(); } console.writeline("your age " + (string.format("{0:00}", (now - bday)))); //it rounds off float console.readline(); } grab (exception ex) { console.writeline(ex.tostring()); console.readline(); } }
}
contrary comments, timespan
not help here, because year not fixed length of time. in turn leads expressed aim beingness unusual indeed. shouldn't representing date fractional number first 2 digits beingness months , 3rd , 4th digits beingness days. time doesn't work that. (consider difference between 2014.0131 , 2014.0201 much greater difference between 2014.0130 , 2014.0131, example.)
it improve represent age in terms of years, months , days. noda time library makes pretty simple:
localdate birthday = new localdate(1976, 6, 19); // illustration localdate today = localdatetime.fromdatetime(datetime.now).date; // see below period period = period.between(birthday, today); console.writeline("you {0} years, {1} months, {2} days old", period.years, period.months, period.days);
if want determine number of years, decide utilize period.years
, or perchance round result based on period.months
well.
i recommend against using datetime.now
in production code, however. in noda time, have iclock
interface representing "a means of getting current instant in time", systemclock
implementation in main assembly , fakeclock
implementation in testing assembly. code take iclock
(possibly dependency injection) , utilize determine current date in whatever time zone you're interested in. way, can write tests situation like, without changing computer's clock. way of handling time-related tasks in general, imo.
c# datetime decimal calculator
Comments
Post a Comment