how to return null datetime - date

I know such questions are repeated but I did not get any result.I must change helical date to Gregorian date and this is my method
public static DateTime ShamsiToMiladi(string shmasi)
{
DateTime? Dt = null;
if (shmasi != "")
{
System.Globalization.PersianCalendar persian = new System.Globalization.PersianCalendar();
char[] spChar = { '/' };
string[] splited_shamsi = shmasi.Split(spChar, 3);
Dt = persian.ToDateTime(int.Parse(splited_shamsi[0]), int.Parse(splited_shamsi[1]), int.Parse(splited_shamsi[2]), 12, 12, 12, 12);
}
return Dt;
}
sahmsi is a parameter that comes from a textbox.what do i return Dt?
thanks for help

Since DateTime is actually a structure built upon a long integer, it cannot be assigned a null value.
But if you need to have that option, declare it as a nullable DateTime thusly:
DateTime? ThisDate = null;
If you do return a nullable DateTime, your caller will have to check for a null value before using as a regular DateTime in expressions.
As a general rule, a newly-declared regular DateTime has a value of DateTime.MinValue ('01/01/0000'), and you can test for that, instead.

Related

Flutter : DateTime.now().toIso8601String() Math

i have DateTime.now().toIso8601String() = 2022-08-09T03:01:32.223255
how can i find if 3 days have passed since the date ?
You can parse string to DateTime object:
final dateTime = DateTime.now();
final stringDateTime = dateTime.toIso8601String();
final parsedDateTime = DateTime.parse(stringDateTime);
In this case, dateTime and parseDateTime are the same.
Then to find out the time difference use difference DateTime instance method, which returns Duration instance. Example from dart documentation:
final berlinWallFell = DateTime.utc(1989, DateTime.november, 9);
final dDay = DateTime.utc(1944, DateTime.june, 6);
final difference = berlinWallFell.difference(dDay);
print(difference.inDays); // 16592
Use the difference function on DateTime object:
DateTime now = DateTime.now();
DateTime addedThreeDays = DateTime.now().add(Duration(days: 3));
print(3 >= now.difference(addedThreeDays).abs().inDays);

How can I use an extended entity to create a new property in my EF6 class with property changed notification?

I have a table in my entity model called prices. It has several fields named value0, value1, value2, value3, value4... (these are their literal names, sigh..). I cannot rename them or in any way change them.
What I would like is to use an extended entity to create a new property called values. This would be a collection containing value1, value2 etc...
To get access to the values I would then simply need to write prices.values[1]
I need property changed notification for this.
So far I have tried this;
public partial class Prices
{
private ObservableCollection<double?> values = null;
public ObservableCollection<double?> Values
{
get
{
if (values != null)
values.CollectionChanged -= values_CollectionChanged;
else
values = new ObservableCollection<double?>(new double?[14]);
values[0] = value0;
values[1] = value1;
values[2] = value2;
values.CollectionChanged += values_CollectionChanged;
return values;
}
private set
{
value0 = value[0];
value1 = value[1];
value2 = value[2];
}
}
private void values_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Values = values;
}
}
The issue comes when trying to set values. if I try to set a value by writing
prices.values[0] = someValue;
The new value is not always reflected in the collection (i.e. when I have previously set value and then try to overwrite the value).
I am willing to try any approach that would achieve my goal, I am not precious about having my solution fixed (although if anyone can explain what I'm missing that would be great!)
You could implement an indexer on Prices class without using a collection.
You can use switch to select the property to write or you can use reflection.
In this case I use reflection.
public double? this[int index]
{
get
{
if (index < 0 || index > 13) throw new ArgumentOutOfRangeException("index");
string propertyName = "Value" + index;
return (double?)GetType().GetProperty(propertyName).GetValue(this);
}
set
{
if (index < 0 || index > 13) throw new ArgumentOutOfRangeException("index");
string propertyName = "Value" + index;
GetType().GetProperty(propertyName).SetValue(this, value);
// Raise your event here
}
}

Display only Date in #Html.DisplayFor() in MVC

I work in MVC5 and EntityFramework for displaying data into View.
right now in my view data format is :- 10/22/2014 12:00:00 AM
But i want only date :- 22/10/2014 in this format
i try this code but it not working
#if (item.chekin_on_after != null)
{ #Html.DisplayFor(modelItem => item.chekin_on_after, "ShortDateTime")}
I also follow few link in stackoverflow but not helpful Date Format using Html.DisplayFor() in MVC5, Display only date and no time
I didn’t use #html.DisplayFor().Instead of this I use
#Convert.ToString(string.Format("{0:dd/MM/yyyy}", item.chekin_on_after))
And it works perfectly.
Try to use below attribute in your model class.
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime chekin_on_after { get; set; }
Hope it helps..
You can use this function in your controller before populating the data to model :
public static System.DateTime ParseDate(string value, string style)
{
DateTime blankDate = default(DateTime);
if ((value != null & value.Length > 0)) {
string formattedDate = Strings.Format(Convert.ToDateTime(value), style);
return formattedDate;
} else {
return blankDate;
}
}
Where value is your: 10/22/2014 12:00:00 AM and style is :"MM/dd/yyyy" or something as you want

Post timestamp param as a Date for Play!Framework Models?

I'd like Play!Framework to convert a Timestamp sent via POST into a java.util.Date format in the Model, but I don't know if it's directly possible.
Here's my model :
public class Contact extends Model {
#Id
private Long id;
#Constraints.Required
private String name;
#JsonIgnore
#Temporal(TemporalType.TIMESTAMP)
private Date removed = null; // When the contact is no longer active
}
I tried to add #Formats.DateTime(pattern="?") to removed, but since DateTime use SimpleDateFormat, I wasn't able to found which pattern to use to convert a timestamp to the correct Date.
How can I do ?
Ok I'll answer myself on this, here's what I did (maybe not the best way to do it, but it works).
I don't use the Model to match the posted param to the removed value, but instead, I do this in my Controller :
String[] accepts = {"name", "datestamp"};
Form<Contact> form = Form.form(Contact.class).bindFromRequest(accepts);
Date date = null;
try {
date = new Date(Long.parseLong(form.field("datestamp").value()));
}
catch (NumberFormatException nfe) {}
if (date == null) {
form.reject("date", "error.invalid");
}
if (form.hasErrors()) {
return badRequest(form.errorsAsJson());
}
else {
Contact contact = form.get();
contact.setRemoved(date);
contact.save();
return ok();
}

Build condition with date for jpa2 typesafe query

I have following query:
SELECT DISTINCT *
FROM Projekt p
WHERE p.bewilligungsdatum = to_date('01-07-2000', 'dd-mm-yyyy')
but i have problems to build the conditions. Here my code:
condition = criteriaBuilder.equal((Expression<String>) projekt.get(criterion), "to_date('" + projektSearchField + "', 'dd-mm-yyyy')");
this generate following:
SELECT DISTINCT *
FROM Projekt p
WHERE p.bewilligungsdatum = 'to_date('01-07-2000', 'dd-mm-yyyy')'
and ufcorse doesn't work. Which method should i use for date comparision (or how to remove the outer ' chars in the pattern part)?
why don't you try to work with parameters like that. Then you can do the String->Date conversion in java and pass a real java.util.Date to the database.
EntityManager em; // initialized somewhere
Date datum; // initialized somewhere
...
String queryString = "SELECT p "
+ "FROM Projekt p"
+ "WHERE p.bewilligungsdatum = :datum";
Query query = em.createQuery(queryString)
query.setParameter("datum", datum);
List<Projekt> projekte = query.getResultList();
This is the way to stay DB independent because your are not using the specific to_date function
viele Grüße aus Bremen ;o)
This should work too, by passing a date as parameter of a restriction
Date datum; // initialized somewhere
CriteriaQuery query = ...
query.add(Restrictions.eq( "bewilligungsdatum ", datum );
...
Sorry. I had the hibernate CriteriaQuery in mind.
Then try via the CriteriaBuilder somthing like that
Date datum; // initialized somewhere
...
final CriteriaQuery<Projekt> query = criteriaBuilder.createQuery(Projekt.class);
final Root<Projekt> projekt = query.from(Projekt.class);
Predicate condition = criteriaBuilder.equals(projekt.get("bewilligungsdatum"),datum);
query.where(condition)
I did not use this before, so have a try on your own
you can use https://openhms.sourceforge.io/sqlbuilder/ ,then use the Condition like
Object value1 = hire_date
Object value2 = new CustomObj("to_date('2018-12-01 00:00:00','yyyy-MM-dd HH:mm:ss')")
//CustomObj
public class CustomObj extends Expression {
private Object _value;
public CustomObj(Object value) {
_value = value;
}
#Override
public boolean hasParens() {
return false;
}
#Override
protected void collectSchemaObjects(ValidationContext vContext) {
}
#Override
public void appendTo(AppendableExt app) throws IOException {
app.append(_value);
}
}
BinaryCondition.greaterThan(value1, value2, inclusive);
the sql like hire_date >= to_date('2011-02-28 00:00:00','yyyy-MM-dd HH:mm:ss'))