How to set a default value to a DateTime parameter - c#

In my MVC application I want to set default values to the DateTime parameter.
[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime startDate)
{
var Odata = _db.sp_BudgetedVsActualTabular(startDate).ToList();
string[] monthName = new string[12];
for (int i = 0; i < 12;i++ )
{
DateTime date = startDate;
date = date.AddMonths(i);
monthName[i] = date.ToString("MMMM") + " " + date.Year.ToString();
}
ViewBag.startDate = new SelectList(_db.DaymonFinancialYears, "startDate", "DateRange");
var MonthName = monthName.ToList();
ViewBag.Bdata = Odata;
ViewBag.Cdata = MonthName;
return View();
}

You cannot set a null to a DateTime but you can use a Nullable DateTime parameter instead:
[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime? startDate = null )
{
if (startDate == null)
{
startDate = new DateTime(2016, 06, 01);
}
//You should pass startDate.Value
var Odata = _db.sp_BudgetedVsActualTabular(startDate.Value).ToList();
}

You can use the default keyword with this syntax
public ActionResult BudgetVSActualTabular(DateTime startDate = default(DateTime))
This will make possible to call the method without passing any parameter and inside your method the startDate variable will be equal to DateTime.MinValue
If you need the default to be a specific date instead of DateTime.MinValue you could write a simple test
public ActionResult BudgetVSActualTabular(DateTime startDate = default(DateTime))
{
if(startDate == DateTime.MinValue)
startDate = new DateTime(2014,6,1);
// After the check for a missing parameter pass the startDate as before
var Odata = _db.sp_BudgetedVsActualTabular(startDate).ToList();
.....
}

Named and optional (default) parameters are available starting from C# 4.0. in case you're using an older version, you may overload your method like:
public ActionResult BudgetVSActualTabular()
{
return BudgetVSActualTabular(new DateTime(2014,6,1));
}

I would suggest setting the DateTime to be nullable public ActionResult BudgetVSActualTabular(DateTime? startDate).
Inside your controller you can use DateTime.HasValue to set a default if the DateTime is null.
var nonNullableDate = startDate.HasValue ? startDate.Value : new DateTime();
[HttpPost]
public ActionResult BudgetVSActualTabular(DateTime? startDate)
{
var nonNullableDate = startDate.HasValue ? startDate.Value : new DateTime();
var Odata = _db.sp_BudgetedVsActualTabular(nonNullableDate).ToList();
string[] monthName = new string[12];
for (int i = 0; i < 12;i++ )
{
DateTime date = nonNullableDate;
date = date.AddMonths(i);
monthName[i] = date.ToString("MMMM") + " " + date.Year.ToString();
}
ViewBag.startDate = new SelectList(_db.DaymonFinancialYears, "startDate", "DateRange");
var MonthName = monthName.ToList();
ViewBag.Bdata = Odata;
ViewBag.Cdata = MonthName;
return View();
}

Related

Copy last value to other cells till we see a filled cell

I have a list like below :
2016-10-05 00:00:00.000
NULL
NULL
NULL
2016-08-12 07:46:00.000
NULL
NULL
Which I need to convert to
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-10-05 00:00:00.000
2016-08-12 07:46:00.000
2016-08-12 07:46:00.000
2016-08-12 07:46:00.000
Basically, I need to capture the last occurrence date and copy it to next rows till i see a filled row.
Here is how I see it working now
foreach (var date in dates)
{
var lastValue = null;
if(date != null)
{
lastValue = date;
}
if(date == null)
{
date = lastValue;
}
else
{
lastValue = date;
}
}
I would use a simple for-loop for this
List<DateTime?> dates = new List<DateTime?>()
{
new DateTime( 2016,10,05,00,00,00),
null,
null,
null,
new DateTime( 2016, 08, 12 ,07,46,00),
null,
null
};
DateTime? latest = null;
for (int i = 0; i < dates.Count; i++)
{
if (dates[i].HasValue)
{
latest = dates[i];
}
else
{
dates[i] = latest;
}
}
https://dotnetfiddle.net/qqDaMf
//input
List<DateTime?> dates = new List<DateTime?> { DateTime.Now, null, DateTime.Parse("2019-10-01"), null };
DateTime? lastPresentDate = dates.FirstOrDefault();
if (lastPresentDate.HasValue)
{
dates = dates.Select(d => d.HasValue ? lastPresentDate = d : lastPresentDate).ToList();
}
//output
7/23/2019 7:15:48 AM
7/23/2019 7:15:48 AM
10/1/2019 12:00:00 AM
10/1/2019 12:00:00 AM
This will only correct the dates if the first date is present and otherwise leave the list as is.
Assuming you actually have a class (let's say Product) with some other properties:
DateTime? lastDate = null;
var result = products.Select(
p =>
new {
Id = p.Id,
CreateDate = (p.CreateDate.HasValue ? (lastDate = p.CreateDate) : lastDate)
//Other properties..
}
);
If not and you have just the dates:
DateTime? lastDate = null;
var result = dates.Select(d => (d.HasValue ? (lastDate = d.Value) : lastDate));
You can add .ToList() if you like or not.
Change String class for whatever class u are using.
String lastValue = null;
foreach(var value in ValuesList){
if(value == null)
value = lastValue;
else
lastValue = value;
}

C# WinForm error import from excel to database

Hei. I need to understand why I receive an error like that :
C# windows form import from excel error
I can't separe the year from string (year time). Or, can I renounce at split and import directly the string as "date"? Sorry, I'm too beginner in c#, but I need this help, is a task for me.
Here is my code :
for (int i = 0; i < dvColumns.Count; i++)
{
string columnName = string.Empty;
string columnField = string.Empty;
if ((dvColumns[i]["Header"] != null) && (!Convert.IsDBNull(dvColumns[i]["Header"])))
{
columnName = dvColumns[i]["Header"].ToString();
}
if ((dvColumns[i]["Field"] != null) && (!Convert.IsDBNull(dvColumns[i]["Field"])))
{
columnField = dvColumns[i]["Field"].ToString();
}
rangeObject = cellsObject.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cellsObject, new object[] { row, i + 1 });
object valueObject = rangeObject.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, rangeObject, null);
if (columnName == "FiscalCode" && columnField == "PartnerId")
{
string fiscalCode = Erp.Core.Utils.GetStringFromObject(valueObject);
partnerId = p.GetPartnerIdByFiscalCode(fiscalCode);
eventRow["PartnerId"] = partnerId;
}
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
DateTime columnDate = DateTime.Now;
string[] dateComponents = null;
int year = 0;
int month = 0;
int day = 0;
if (date.Contains("."))
{
dateComponents = date.Split('.');
}
if (date.Contains("/"))
{
dateComponents = date.Split('/');
}
if (date.Contains(":"))
{
dateComponents = date.Split(':');
}
if (dateComponents.Length > 1)
{
string s = dateComponents[0];
day = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[1];
month = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[2];
year = Erp.Core.Utils.GetIntFromObject(s);
columnDate = new DateTime(year, month, day, 9, 0, 0);
}
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
}
I tried to keep in excel same format as in database table : 'yyyy/mm/dd hh:mm:ss.000'.
The line date = Erp.Core.Utils.GetStringFromObject(valueObject); get my date from first excel cell.
ds.Tables["Events"] is all time empty.
I know this line eventRow[columnField] = date; must add the dates in DB, really? After split, day is ok (receive an int by s[0]), month is ok (receive an int by s[1], but s[2] for year is something like 2017 19:06:22 .... year plus time). I tried to split again by space, but without results, to keep the number (2017) in year variable.
Best way is to use DateTime.ParseExact method. In your case, if original format is 'yyyy/mm/dd hh:mm:ss.000', you can convert it to DateTime like this:
//string date = Erp.Core.Utils.GetStringFromObject(valueObject);
string date = "2017/08/15 10:20:30.000";
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
This way you can skip parsing excel string.
In your example, usage will be like this:
//...snip...
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
//parsing date string
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
if hours are in 12-hour format, use lowercase hh, like this "yyyy/MM/dd hh:mm:ss.fff"

How to determine if the value of datetime is valid(full date) or it is in year only?

DATETIME Value 1980
I have this code to retrieve a DateTime from sql
string startDate = ed.IDAFrom != null ? Convert.ToDateTime(ed.IDAFrom).ToShortDateString() : "";
EDIT
Note: The Date here is Year Graduated (must be in full date)
I have a datepicker in my view(so the date is in full date right?).. What if the user forgot the date when he graduate so the user will be edit the datepicker to year only.
What I want to achieve here is if the user encode full date or year I want to get the value of YEAR if the user encode full date.
Hope it clears.
Thanks.
Code
foreach (var ed in exams)
{
int rowId = i;
string startDate = ed.IDAFrom != null ?Convert.ToDateTime(ed.IDAFrom).ToShortDateString() : "";
string endDate = ed.IDATo != null ? Convert.ToDateTime(ed.IDATo).ToShortDateString() : "";
string InclusiveDates = startDate + " - " + endDate;
rowsObj[i] = new { id = rowId, cell = new object[] { rowId, InclusiveDates } };
i++;
}
I want to display the year only if it is in full date.
DateTime value;
if(DateTime.TryParse(ed.IDAFrom, out value))
{
Int year = value.Year;
}
If you care about culture:
CultureInfo = CultureInfo.CreateSpecificCulture("en-US"); // Or whichever culture you need
if (DateTime.TryParse(ed.IDAFrom, culture, DateTimeStyles.None, out value))
{
int year = value.Year;
}
If the user has the option to either enter year only or a full date, use this method:
public static string GetDateTime(string value)
{
DateTime date;
string dateString = ""; // Empty by default
// If full date is given, this will succeed
if (DateTime.TryParse(value, out date))
{
dateString = date.ToShortDateString();
}
// If only year is given then this will succeed
else if (DateTime.TryParseExact(value,
"yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
dateString = date.ToShortDateString();
}
return dateString;
}
EDIT
Now that you have added some more code to your question, here is how to do it using Linq:
int i = 0;
int j = 0;
var rows = list.Select(exam =>
{
string inclusiveDates = string.Format("{0} - {1}", GetDateTime(exam.IDAFrom), GetDateTime(exam.IDATo));
return new
{
Id = ++i,
Cell = new object[] { ++j, inclusiveDates }
};
})
.ToList();
And here is an example usage
class Program
{
public class Exam
{
public string IDAFrom { get; set; }
public string IDATo { get; set; }
}
public static string GetDateTime(string value)
{
DateTime date;
string dateString = ""; // Empty by default
// If full date is given, this will succeed
if (DateTime.TryParse(value, out date))
{
dateString = date.ToShortDateString();
}
// If only year is given then this will succeed
else if (DateTime.TryParseExact(value,
"yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
dateString = date.ToShortDateString();
}
return dateString;
}
static void Main(string[] args)
{
var list = new List<Exam> { new Exam { IDAFrom = "1999", IDATo = null },
new Exam { IDAFrom = DateTime.Now.ToShortDateString(), IDATo = DateTime.Now.AddDays(5).ToShortDateString() } };
int i = 0;
int j = 0;
var rows = list.Select(exam =>
{
string inclusiveDates = string.Format("{0} - {1}", GetDateTime(exam.IDAFrom), GetDateTime(exam.IDATo));
return new
{
Id = ++i,
Cell = new object[] { ++j, inclusiveDates }
};
})
.ToList();
foreach (var item in rows)
{
Console.WriteLine("{0}\t{1}\t{2}", item.Id.ToString(), item.Cell[0], item.Cell[1]);
}
Console.Read();
}
}

convert timespan to datetime

My function is :
public async Task<IHttpActionResult> RecentAddedTags(int daysago)
{
TimeSpan duration = DateTime.UtcNow - DateTime.Today.AddDays(-daysago);
DateTime days = DateTime.UtcNow - duration;
var ret = from tag in db.Tags
where tag.time.Equals(days)
select new
{
postedById = tag.AspNetUser.Id,
postedByName = tag.AspNetUser.UserName,
name = tag.name,
info = tag.info,
time = tag.time,
id = tag.Id,
};
return Ok(ret);
}
If I call the function as RecentAddedTags(2) it should return all tags created 2 days ago. But it gives the error:
Unable to create a constant value of type 'System.Object'. Only
primitive types or enumeration types are supported in this context.
There is some issue with days object. What I am doing wrong?
Compare Date in DateTime Object it will work for you
var ret = from tag in db.Tags.ToList()
where tag.time.Date == days.Date
select new
{
postedById = tag.AspNetUser.Id,
postedByName = tag.AspNetUser.UserName,
name = tag.name,
info = tag.info,
time = tag.time,
id = tag.Id,
};
You need to change
tag.time.Equals(days)
to
tag.time == days;
(not entirely sure why it works)

Convert DateTime To JSON DateTime

I have a WebService which return DateTime Field.
I get a result /Date(1379048144000)/ but
i want just 1379048144000 how can i achieve that.
[WebMethod]
public DateTime GetServerDate()
{
return DateTime.Now;
}
by setting Header Content-Type: application/json; charset=utf-8; i got a result like /Date(1379048144000)/.
You could change your WS to return a long with the value of the DateTime. The value to return is the number of milliseconds since the Unix Epoch (01/01/1970). This could be done with an extension method on DateTime something like:
public static class DateTimeExtensions
{
...
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static long ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).Ticks / TimeSpan.TicksPerMillisecond;
}
...
}
And your web service method might look something like:
public long GetMyDate(...)
{
DateTime dateTime = ...;
return dateTime.ToUnixTime();
}
with Json.NET :
string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);
in client side you can use this function to show a right date to client(I use it on my projects):
function parseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined) parts[2] = 0;
if (parts[3] == undefined) parts[3] = 0;
d = new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
date = d.getDate() + 1;
date = date < 10 ? "0" + date : date;
mon = d.getMonth() + 1;
mon = mon < 10 ? "0" + mon : mon;
year = d.getFullYear();
return (date + "." + mon + "." + year);
};
This function is return right date in format: dd.mm.yyyy, but you can change it if you need. I hope that I help you.
U can always solve your problem when sending a date in a JSON object to JS by converting the date as follows:
var myJSDate = (new Date(parseInt(obj.MyDate.substr(6)))).toJSON();
Where obj.Date contains the date you wanna format.
Then u'll get something like this: "2013-10-25T18:04:17.289Z"
U can always check it in Chrome console by writing:
(new Date()).toJSON();
Hope this helps!
There are two solutions:
client side:
function ToJavaScriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
It is possible to need alsou to convert into data object
var date = new Date(xxx)
Server side:
Newtonsoft.Json.JsonConvert.SerializeObject(your_object)
Simply write like this to convert your date string in JSON format.
date = "{" + date + "}";
try regex:
var jsonDate = #"/Date(1379048144000)/";
var regex = /-?\d+/;
var jsonDate = re.exec(jsonDate);
var dateOriginal = new Date(parseInt(m[0]));

Categories