How do I calculate the age of the user in Powershell - function

I'm trying to write a function in Powershell where I calculate the age of the user based on the birthdate. So it should probably be currentdate - birthdate and put the difference in years. I'm getting stuck however, on the formating of these dates because the user has to input their birthdate.
Function getAge ($birthDate)
{
$currentDate = Get-Date
$age = $currentDate - $birtDate
Write-Host "Your age is $age"
}
getAge 24-01-1991

Your function is almost there, except for the fact that it creates and returns a TimeSpan object with the difference between the current and the given date.
Try
function Get-Age {
param (
[Parameter(Mandatory = $true)]
[datetime]$birthDate
)
$currentDate = Get-Date
$age = $currentDate - $birthDate
# use the ticks property from the resulting TimeSpan object to
# create a new datetime object. From that, take the Year and subtract 1
([datetime]::new($age.Ticks)).Year - 1
}
# make sure the BirthDate parameter is a valid DateTime object
Get-Age ([datetime]::ParseExact('24-01-1991', 'dd-MM-yyyy', $null))

First you need to convert the input parameter $birthDate, currently a string, to a DateTime object, for that you can use the ParseExact(..) method. Then you need to decide which type of date format your function will accept, I have added a ValidatePattern attribute to the function so that currently only accepts the pattern shown in your question, this however can be updated so that the function takes more than one format (ParseExact(..) can also parse multiple formats). Lastly, you're correct with Current Date - Birth Date, this will get us a TimeSpan object which has a .Days property, we can use the value of the property and divide it by the number of days in a year to obtain the user's age.
function getAge {
[cmdletbinding()]
param(
[ValidatePattern('^(\d{2}-){2}\d{4}$')]
[string]$birthDate
)
$parsedDate = [datetime]::ParseExact(
$birthDate,
'dd-MM-yyyy',
[cultureinfo]::InvariantCulture
)
[int] $age = ([datetime]::Now - $parsedDate).Days / 365
Write-Host "Your age is $age"
}
getAge 24-01-1991

Related

Newtonsoft deserializing Json incorrectly

I have encountered a case where Newtonsoft is taking perfectly valid JSON text, but deserializing it incorrectly. I have an object that contains an embedded class that consists of members Year, Month, Week, and DayOfWk. The JSON looks like this:
"openDate": {
"Year": 1997,
"Month": 12,
"Week": 5,
"DayOfWk": 5
},
But the data that comes back after deserialization is Year = 1, Month = 1, Week = 1, and DayOfWk = 1, regardless of the input JSON.
Here is the code (it's in F#, but should be easily readable):
let jsonText = File.ReadAllText( #"..\..\..\..\Dependencies\ADBE.dat")
let dailyData = JsonConvert.DeserializeObject<DailyAnalysis[]>(jsonText)
DailyAnalysis is defined as:
type DailyAnalysis = {
openDate: TradeDate
openPrice: Decimal
closeDate: TradeDate
closePrice: Decimal
gainPercentage: Decimal
}
TradeDate is the class in question - it is an F# class that exposes properties Year, Month, Week, and DayOfWk. Year, Month, and Week are int's; DayOfWeek is a DayOfWeek enum. All the other fields in the DailyAnalysis objects come back with the correct values.
How can this problem be resolved?
Note that if I don't include the type in the DeserializeObject call, it does get the correct data, but simply returns it as an object, and converting to the correct type is very difficult (i.e., I don't know how to do it in F#).
Can anybody point out something obvious (or even obscure) I'm overlooking, or point me to other resources?
Update: note that the constructor for TradeDate takes a single DateTime argument.
Assuming that your TradeDate is immutable (as typically happens in f#), then Json.NET is able to deserialize such a type by finding a single constructor which is parameterized, then invoking it by matching constructor arguments to JSON properties by name, modulo case. Arguments that do not match are given a default value. If TradeDate actually takes a single DateTime as input, you will get the behavior you are seeing.
For instance, if we take a simplified version like so:
type TradeDate(date : DateTime) =
member this.Year = date.Year
member this.Month = date.Month
member this.DayOfMonth = date.Day
And then round-trip it using Json.NET as follows:
let t1 = new TradeDate(new DateTime(1997, 12, 25))
let json1 = JsonConvert.SerializeObject(t1)
let t2 = JsonConvert.DeserializeObject<TradeDate>(json1)
let json2 = JsonConvert.SerializeObject(t2)
printfn "\nResult after round-trip:\n%s" json2
The result becomes:
{"Year":1,"Month":1,"DayOfMonth":1}
Which is exactly what you are seeing. Demo fiddle #1 here.
So, what are your options? Firstly, you could modify TradeDate to have the necessary constructor, and mark it with JsonConstructor. It could be private as long as the attribute is applied:
type TradeDate [<JsonConstructor>] private(year : int, month : int, dayOfMonth: int) =
member this.Year = year
member this.Month = month
member this.DayOfMonth = dayOfMonth
new(date : DateTime) = new TradeDate(date.Year, date.Month, date.Day)
Demo fiddle #2 here.
Secondly, if you cannot modify TradeDate or add Json.NET attributes to it, you could introduce a custom JsonConverter for it:
[<AllowNullLiteral>] type private TradeDateDTO(year : int, month : int, dayOfMonth : int) =
member this.Year = year
member this.Month = month
member this.DayOfMonth = dayOfMonth
type TradeDateConverter () =
inherit JsonConverter()
override this.CanConvert(t) = (t = typedefof<TradeDate>)
override this.ReadJson(reader, t, existingValue, serializer) =
let dto = serializer.Deserialize<TradeDateDTO>(reader)
match dto with
| null -> raise (new JsonSerializationException("null TradeDate"))
| _ -> new TradeDate(new DateTime(dto.Year, dto.Month, dto.DayOfMonth)) :> Object
override this.CanWrite = false
override this.WriteJson(writer, value, serializer) =
raise (new NotImplementedException());
And deserialize as follows:
let converter = new TradeDateConverter()
let t2 = JsonConvert.DeserializeObject<TradeDate>(json1, converter)
Demo fiddle #3 here.
Notes:
Your question did not include code for TradeDate, in particular the code for converting between a DateTime and the year/month/week of month/day of week representation. This turns out to be slightly nontrivial so I did not include it in the answer; see Calculate week of month in .NET and Calculate date from week number for how this might be done.
For details on how Json.NET chooses which constructor to invoke for a type with multiple constructors, see How does JSON deserialization in C# work.

How to take Date from sql db as a single result and compare with current date

i have a complex problem with Date field. Describe what i want to do:
I have field date1 as Date in my db.
#Temporal(TemporalType.DATE)
private Date date1;
I want to take data from this field and compare with current date.
#Query("SELECT date1 FROM Table io WHERE io.date1 >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-%e')")
Date findAll2();
public boolean CheckDate1(){
currentDate = new Date();
date1 = getInterimOrdersRepo().findAll2();
if(currentDate.before(date1) || currentDate.equals(date1)){
System.out.println("TRUE");
System.out.println("currentDate = "+currentDate);
return true;
}
else{
System.out.println("FALSE");
return false;
}
}
but i have an error:
result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException
When method return false i want do Update field data1 with " " empty data.
I using jsf, what i must to do?
It seems that you are trying to read several values from the table into a single variable, and that is the error.
findall2 returns an array (most likely) and u should read one of it's values - try reading first one.
Furthermore, I believe that you can skip the "DATE_FORMAT" in your query, and this is a very strange way to write a code. Not clear what u are trying to achieve here

Setting the date in an HTML5 date input

I'm trying to progamatically set the date in an HTML5 date input using ajax and javascript. I have an ajax/php call that returns the date that I want in a string variable in the format "YYYY-MM-DD". I can't seem to make this work. Here is my attempt:
var myDate = "2013-07-10" //actually is returned by my ajax call, but same idea
//set the date value
var thisDate = new Date();
thisDate.setFullYear(parseInt(workout_date.split("-")[0]));
thisDate.setMonth(parseInt(workout_date.split("-")[1])-1);
thisDate.setDate(parseInt(workout_date.split("-")[2]));
document.getElementById("date_input").value = thisDate;
I'm not getting any errors, but my date input just remains at the default (mm/dd/yyyy). Anyone know what I am doing wrong? Thanks!
You're trying to set the value of the date to a Date object. But the date input, like other inputs, can only accept strings:
If the user agent provides a user interface for selecting a date, then the value must be set to a valid date string representing the user's selection. [Emphasis added.]
In this case, myDate represents a valid date string, so you can use it directly.

DateField: selectedDate shows hours as 24:00:00

With a DateField component, the selectedDate.getHours returns as 24:00:00. I want it to return as 00:00:00.
Is there an easy way to do this?
Thanks!
UPDATE:
First, I set a variable in my Model that equals the selectedDate of a DateField component:
model.generalInfo.endDate = endDate_df.selectedDate;
Then I set another variable based on that value and I trace it out:
param.todate = df.format( model.generalInfo.endDate.toString() );
And this is where I see the time equal to 24:00:00
you could try something like
selectedDate.time = selectedDate.time - 24 * 60 * 60 * 60 * 1000
as a Date.time represents miliseconds since 1970 or whatever.. you substract 24 hours..
if it not works for you, you can create a new function or getter that converts it, or you can create a new mxml module, with DateField as superclass, and you can override the getHours method. tons of options to do this..
It looks like you are using the Flex DateFormatter to format the Date object. Have a look at the docs for this class, it has a formatString property that you can use to control how to output the date (or in this case the time).
If you give the DateFormatter a format string that contains "H" will output the hour in 24 hour format using the number range 1-24. If the format string contains "J" it will output the hour in 24 hour format using the range 0-23.
To get your desired output, use "JJ" in the format string, in addition to any other items. For example to output the hours, minutes, seconds:
var someDate:Date = new Date(2012, 11, 5);
var df:DateFormatter = new DateFormatter();
df.formatString = "JJ:NN:SS";
var formatted:String = df.format(someDate); // 00:00:00
Also, as #Flextras mentioned, there is Flash localization API you can use which has the added benefit of converting date/time strings to the values used by their locale. These are the DateTimeFormatter classes:
fl.globalization.DateTimeFormatter
spark.formatters.DateTimeFormatter (Flex 4)
These classes format dates into the user's locale (or one that you specifcy), and format Date objects the same way the DateFormatter does.

How to convert date in Text box to MySQL DATETIME format

I'm quite new to php and have been reading Larry Ullman book to develop a basic db site.
I have used the YUI Calendar pop up date picker to add a date to a text field called"date". The date format it enters is eg Thursday, 7 May 2009
I have tried many different ways to try and enter the date in to mysql db but it remains at 00 00 00 00 00 00
This is the code related to the date field I have,
// Check for a Date.
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo '<p><font color="red">Please enter a valid Date!</font></p>';
}
// Add the URL to the urls table.
$query = "INSERT INTO urls (url, title, description, date) VALUES ('$u', '$t', '$d', '$p')";
$result = #mysql_query ($query); // Run the query.
$uid = #mysql_insert_id(); // Get the url ID.
if ($uid > 0) { // New URL has been added.
I think I have provided all pertinent information but again apologies if this isn't helpful and I will do my best to provide yo with any other information you may require.
Thanks - Sean
If the format that your date picker is passing in is "Thursday, 7 May 2009", then the strtotime() and date() functions should work to give you a valid date to pass to MySQL:
$p = date("Y-m-d H:i:s",strtotime('Thursday, 7 May 2009'));
If your database field is a DATE, you probably only want the "Y-m-d" part. If it's a DATETIME, you'll want the "H:i:s" as well.
You probably need to format the date in the way that mysql expects it for that datatype, or else it cannot recognize it. You could use a regex or similar method to extract the component parts and format it according to the format of the MySQL DATETIME type.
EDIT: See http://dev.mysql.com/doc/refman/5.0/en/datetime.html for said format. Also, you might be better off storing the date/time as a unix timestamp, as that usually is easier to maintain.
the date format in mysql is YYYY-MM-DD, so change the way you accept data on php
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';
Should be
if (eregi ("^([0-9]{4}/([0-9]{2})/([0-9]{2}))$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';