In Angular js how to convert Date format - c#

public JsonResult GetAll()
{
Entities contextObj = new Entities();
var employeeList = contextObj.CCFFares.ToList();
//return Json(employeeList, JsonRequestBehavior.AllowGet);
return this.Json((from obj in contextObj.CCFFares
select new
{
ID = obj.ID,
Departure_Airport = obj.Departure_Airport,
Destination = obj.Destination,
Departure_Date = obj.Departure_Date.ToString(),
Return_Date = obj.Return_Date.ToString(),
Airline = obj.Airline,
Fare = obj.Fare,
Offer_Ends = obj.Offer_Ends,
Ailine_Class = obj.Airline_Class
}), JsonRequestBehavior.AllowGet);
}
I got an issue where i need to show the date in dd/mm/yy but i am receiving in this manner 2/20/2017 12:00:00 AM what i really dint want to and when i bind the value in view without to string conversion i do get the date time in this way " /Date(1479600000000)/ "where i need to show the date in dd/mm/yy simply can someone guide me on this please !

While binding to your html view use date filter as follows
{{your date in milliseconds| date:'dd/MM/yyyy'}}

Keep .toString() as it is
Try by adding custom filter for date
Angular code
app.filter('filterDate', ['$filter', function ($filter) {
return function (input, format) {
return (input) ? $filter('date')(input, format) : '';
};
Your Html should be like
<li class="mark"> {{Departure_Date | filterDate : 'dd-MM-yy' }}</li>

Related

Date displaying in weird way when adding milliseconds

So in my application I extract data from a database and then extract it to a csv file and I say what I want under each columns like so:
public List<ExtractDocument> GetExtractDocuments(List<Guid>ItemDetailIds)
{
var items = GetExtractData(ItemDetailIds);
return items.Select().Select(item => new ExtractDocument
{
ItemDetailId = item.Field<Guid>("ItemDetailID"),
ItemNumber = item.Field<string>("Number"),
ItemTitle = item.Field<string>("Title"),
ItemRevision = item.Field<string>("RevisionNumber"),
ActionType = item.Field<string>("Action"),
ActionedBy = item.Field<string>("ActionedBy"),
ActionedDate = item.Field<DateTime?>("ActionedDate")?.ToString("dd/MM/yyyy HH:mm:ss.fff"),
Comment = item.Field<string>("Comment"),
TaskType = item.Field<string>("TaskType"),
StartDate = item.Field<DateTime?>("StartDate")?.ToString("dd/MM/yyyy HH:mm:ss.fff"),
CompletedDate = item.Field<DateTime?>("CompletedDate")?.ToString("dd/MM/yyyy HH:mm:ss.fff"),
Status = item.Field<string>("Status"),
Outcome = item.Field<string>("Outcome"),
ActionerName = item.Field<string>("TaskActionedBy"),
DateActioned = item.Field<DateTime?>("ActionDate")?.ToString("dd/MM/yyyy HH:mm:ss.fff"),
ActionTaken = item.Field<string>("TaskAction"),
TaskComment = item.Field<string>("TaskComment"),
Link = item.Field<string>("URL")
}).ToList();
}
This is working but when I open up the csv file and look under the date columns such as "ActionedDate" the date is showing up in a weird way, for example one of the values should be showing as: 03/03/2022 09:07:46 but it is showing in the field as:07:46.3, why is it doing this and how I can prevent that from happening? it doesn't do this for all the fields but it does for the majority
Yeah this was a face palm moment, just realised I had the format written as: "dd/MM/yyyy HH:mm:ss.fff" when it should be "dd/MM/yyyy HH:mm:ss:fff", changing it from ss.fff to ss:fff, fixed the issue

convert Data between ActionResult and View

In my project i use kendo grid to show data and in my ActionResult i use this code to get data :
public ActionResult ShowData([DataSourceRequest] DataSourceRequest request, long studentid)
{
IQueryable<Models.Registration.RegistrationModel>
query =
from financeItem in db.RegistrationItems
select new Models.Registration.RegistrationModel
{
RegisterId = financeItem.RegistrationId,
Id = financeItem.Registration.Id,
Date = financeItem.Registration.Date,
StudentName = financeItem.Registration.Student.FirstName + " " + financeItem.Registration.Student.LastName
};
DataSourceResult dsr = query.ToDataSourceResult(request);
return Json(dsr, JsonRequestBehavior.AllowGet);
}
so . I need convert date to local date and I have a problem.
this is my problem :
when I want convert date inside query I get many error that linq2sql can't find converter function. so I change query type from IQueryable to list and try convert . but I get time out error because I've got a lot of records.
after this error I try convert data inside get and set property in viewmodel like this code :
public string DateSs
{
get
{
return DateConvertor(Date.ToString());
}
set { value.ToString(); }
}
and I use this property inside view and show converted data.
Everything works fine so far but when I want use filter part in kendo grid and filter data base on input date I get and error that this filed not exited in query.
so I have a Headache and I don't know what must I do and how can I convert this dame date
For Kendo Grid your Date column is representation for DateSs instead of Date. When it tries to apply filter on Date, it is applying filter on DateSs which doesn't exist in database table and throws error if defined in your query.
I think the solution for that would be to intercept the DataSourceRequest before applying ToDataSourceResult and change the value and filter name accordingly
UPDATE
The filter Kendo Grid sent is in request.Filters but the structure is hierarchical to support multiple Filters in one request. So, first of all you might want to flatten the filter out, you can use this code to that,
public static IEnumerable<IFilterDescriptor> FlattenFilters(this DataSourceRequest request)
{
return request.Filters
.RecursiveSelect(
descriptor => (descriptor as CompositeFilterDescriptor)?.FilterDescriptors ?? Enumerable.Empty<IFilterDescriptor>(),
descriptor => descriptor as FilterDescriptor)
.Where(x => x != null);
}
This function will return an Enumerable of all the filters currently applied. Then you can change the name of filter like this
request.FlattenFilters().Each(x =>
{
FilterDescriptor filter = x as FilterDescriptor;
if (filter != null && filter.Member == "DateSs")
{
filter.Member = "Date";
//Change the filter.Value property according to your case
//i.e. It would be in String and you might want to convert it to date too.
}
});

assign values from table to Dhtmlx scheduler config

I'm a beginner with dhtmlx scheduler, I use dbfirst with mvc4 razor syntax.
So please can anybody help me to set the start time and endtime values I'm getting from the database:
here is my code:
controller:
sched.Config.first_hour = 8;
sched.Config.last_hour = 19;
public string GetDbValues()
{
string strState = "";
List<tblSettings> settings = new List<tblSettings>();
settings = _config.GetSettings();
var defaultState = from setting in settings
where (setting.Desc == "start time"
|| setting.Desc == "end time")
// starttime as 08 and end time as 20 from database
select setting.Settings;
foreach (var oState in defaultState)
{strState += oState + "|";
}
strState = strState.Remove(strState.Length - 1);
return strState;
}
I get the values for first_hour and last_hour as string from the output.
How to assign this string value to the first_hour and last_hour?
//I use linq to get the db values because of the table structure:
ID(int), Settings(nvarchar) ,Desc (nvarchar)
why do you concatenate the settings into string? More comprehensive data format will simplify the task. You could return List as it is and then just iterate it with foreach, applying needed settings. If for some reason you don't want to pass tblSettings objects, you can select data into Dictionary and then again, apply the values
var data = _config.GetSettings().ToDictionary(
s => s.Desc,
s => s.Setting,
StringComparer.Ordinal);
if(data.ContainsKey("start time"))
scheduler.Config.first_hour = int.Parse(data["start time"]);
if (data.ContainsKey("end time"))
scheduler.Config.first_hour = int.Parse(data["end time"]);

Date format in LINQ

i got problem with my LINQ to format date. Here is code
var resultCustomer = from row in formDg.dtCustomer.AsEnumerable()
where row.Field<int>("customerID") == customerID2
select new
{
name = row["customerName"].ToString(),
ic = row["customerIC"].ToString(),
add1 = row["customerAdd1"].ToString(),
add2 = row["customerAdd2"].ToString(),
tel = row["customerTel"].ToString(),
tel2 = row["customerTel2"].ToString(),
tel3 = row["customerTel3"].ToString(),
email = row["customerEmail"].ToString(),
dateRegister = row["customerDateRegister"].ToString(),
customerRef = row["customerRef"].ToString(),
customerGroup = row["groupCustName"].ToString(),
panelName = row["panelName"].ToString(),
};
var firstRecord = resultCustomer.First();// My record return single row only
My question is how i can format custom date like "dd/MM/yyyy" in customerDateRegister?, Because I got problem when my textbox show 16-Nov-12 12:00:00 AM. I don`t want to display time but just date only.
I have try like this tbDateRegOv.Text = firstRecord.dateRegister.ToString("dd/MM/yyyy");. not work. Then i try dateRegister = row["customerDateRegister"].ToString("dd/MM/yyyy"), in LINQ. Same problem.
So how can I solved this problem? Thanks for help. :)
You need to cast your row as a DateTime first. This will allow you to use the custom format strings for dates.
dateRegister = ((DateTime)row["customerDateRegister"]).ToString("dd/MM/yyyy")
If customerDateRegister is of type DateTime you should make it a DateTime in the first place. Therefor use the DataRow extension method Field<T>:
dateRegister = row.Field<DateTime>("customerDateRegister")
You could try this , replace your dateRegister line with this.
dateRegister = ((DateTime)row["customerDateRegister"]).ToString("dd/MM/yyyy"),
Or, you can use MaskedEditBox with the desired datetime mask

converting .NET DateTime object to Javascript Date object

I've the following problem:
I retrieve a DateTime object from SQL Server and pass it via JSON (using $.ajax) to Javascript. I have experienced difficulty trying to convert the retrieved object to a Date object in javascript.
The retrieved object is a string of value "/Date(615592800000)/". I think the value is an epoch time.
My question is, is there another way of retrieving the date object than to use regex to select the epoch value and then create a new Date object?
I'm fairly new to JS, so any help would be appreciated.
not that I know... this is the function i'm using, just in case ...
function toDateFromJson(src) {
return new Date(parseInt(src.substr(6)));
}
Try this. Pass the date string which you get to the below function. It will give you the JavaScript date object.
function (val) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
if (val)) {
var a = reISO.exec(val);
if (a) {
val = new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
return val;
}
a = reMsAjax.exec(val);
if (a) {
var b = a[1].split(/[-+,.]/);
val = new Date(b[0] ? +b[0] : 0 - +b[1]);
return val;
}
}
return val;
}
This is because JSON as standard does not have a DateTime format - vendors are free to mark it down as they want. WCF has this weird format of /Date()/
I faced this just a couple of months ago.
Using Jquery and Jquery UI it will look like that. controlId is the identifier of an element with
var converted = eval(original.replace(/\/Date\((\d+)\)\//gi, 'new Date($1)'));
The regex way is the perfectly correct way to go.
var msDateRegex = /"\\\/Date\((-?\d+)\)\\\/"/g;
var msDateJsonConverter = function(data) {
return JSON.parse($.trim(data.replace(msDateRegex, '{"__date":$1}')), function(key, value) {
return value && typeof value.__date == "number" ? new Date(value.__date) : value;
});
};
$.ajaxSetup({ converters: { "text json": msDateJsonConverter } });
See: http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx

Categories

Resources