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
Related
My first time working with DateTime in C#. We print out delivery tickets and because our system runs on UTC, I need to convert the date on the ticket back to local time so that tickets with an Estimated Arrival after 6:00PM dont show up as the next day.
I've gotten the timezone from the well and now I am struggling with how to inject the new timezone into my new view model for the ticket.
The error I get is:
After reading, I understand that my truck.EstimatedArrival may be nullable so i tried to insert an .HasValue but so far I can't get the syntax to work for me. Any suggestions on how I need to lay this out?
public async Task<DispatchTruckTicketViewModel> GetDeliveryTruckTicket(string truckId)
{
var truck = await _dispatchTruckRepo.GetDispatchTruckForTicket(truckId);
var dispatchId = await _dispatchRepo.GetAllQueryable()
.Include(did => did.SourceWell.Id)
.SingleOrDefaultAsync(did => truck.DispatchId == did.Id);
var well = await _wellRepo.GetAllQueryable()
.SingleOrDefaultAsync(w => w.Id == dispatchId.SourceWellId);
TimeZoneInfo tz;
tz = TimeZoneInfo.FindSystemTimeZoneById(well.TimeZoneName);
if (truck.EstimatedArrival.HasValue){
TimeZoneInfo.ConvertTimeFromUtc(truck.EstimatedArrival, tz);
} -- still not working, same error as above.
if (truck == null)
{
throw new ServiceException("Truck does not exist");
}
var model = new DispatchTruckTicketViewModel
{
Id = truck.Id,
Type = "Delivery",
TicketNumber = truck.TicketNumber,
OrderedBy = await _accountService.GetNameFromUserId(truck.Dispatch.Header.CreateUserId),
// DateShipped = truck.EstimatedArrival?.ToLocalTime().ToShortDateString() ?? "",
DateShipped = TimeZoneInfo.ConvertTimeFromUtc(truck.EstimatedArrival, tz).ToShortDateString() ?? "",
Items = _mapper.Map<IEnumerable<DispatchItem>, IEnumerable<DispatchItemViewModel>>(truck.Items),
DriverName = truck.DriverName,
SwamperName = truck.SwamperName,
};
AddWellInformation(model, truck.Dispatch.DestinationWell);
return model;
}
The correct way is:
TimeZoneInfo tz;
tz = TimeZoneInfo.FindSystemTimeZoneById(well.TimeZoneName);
if (truck.EstimatedArrival.HasValue){
TimeZoneInfo.ConvertTimeFromUtc(truck.EstimatedArrival.Value, tz);
}
else
{
// Handle failure of getting estimated time
}
HasValue of a nullable value type returns true when the element has a value (is not null). To get the value, you need to call its Value property. As a shortcut, you might use the GetValueOrDefault() method.
for a legacy system, I need to return an object than have inside it a key value than it's the date, and inside have a body, any idea how to get the job done?
I need to return this array
{
"sellerId":"157747190185796800",
"data":
{
"2020-08-25":{ "sales":195000,"comission":25350},
"2020-08-26":{"sales":70500,"comission":9165},
"2020-08-27":{ "sales":51000,"comission":6630}
}
}
I'm trying with a json result and it works, but there's a problem with the key value date
Edit: I'm trying to make the suggestion of an dictionary, but, I don't know what I'm doing bad in this case. i try as an object too and doesn't work.
var lst = new List<Dictionary<string, JsonResult>>();
foreach (var item in listToReturn)
{
lst.Add(new Dictionary(item.DateFromStr, new JsonResult (new
{
sales = item.sales,
comission = item.Comission,
})));
}
I would create the JSON using anonymous objects, using a Dictionary for the sales data like this:
var resultToReturn = new
{
sellerId,
data = listToReturn.ToDictionary (
item => item.DateFromStr,
item => new
{
sales = item.Sales,
commission = item.Commission
}
)
};
Then you can serialize resultToReturn using your favorite serializer, or if you're using MVC, return it in a JsonResult.
Demo fiddle: https://dotnetfiddle.net/jZvoNo
Note: this solution assumes all the date values will be unique within the list, otherwise ToDictionary will throw an exception.
i am getting json result from third party application for integration , it return the value as below. how i can get below json to dataset
{
"Return": {
"InvoiceDetails": {
"Invoiced": "20180930",
"InvoiceID": "",
"Amount": "0.00 "
}
Below is the c# code.
using (var streamInvoiceReader = new StreamReader(httpinvoiceResponse.GetResponseStream()))
{
var responseInv = streamInvoiceReader.ReadToEnd();
DataSet SetInvoice = JObject.Parse(responseInv)["InvoiceDetails"].ToObject<DataSet>();
if (SetInvoice != null && SetInvoice.Tables.Count > 0)
{
grvInvoice.DataSource = SetInvoice.Tables[0];
}
}
In responseInv i can see the return string and it is correct but not able to get it in dataset. there is any difference from result to return? How i can get the data from return array?
thanks in advance.
to solve this problem you should attention to first part of the JSON by [0]
DataSet SetInvoice = JObject.Parse(responseInv)[0]["InvoiceDetails"].ToObject<DataSet>();
Above question i got it working as different way, what i did is :
using (var streamInvoiceReader = new StreamReader(httpinvoiceResponse.GetResponseStream()))
{
var responseInv = streamInvoiceReader.ReadToEnd();
dynamic ResultInvMain = JsonConvert.DeserializeObject(responseInv );
datetime Invoiced = ResultInvMain .Return.InvoiceDetails.Invoiced;
string InvID = ResultInvMain .Return.InvoiceDetails.InvoiceID;
}
and work around with the returned data.
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>
I am trying to make a dynamic linq query that will check for values based on a string.
First of all, here's the query:
objQry = from o in m_Db.OBJECTS.Where(whereConditions)
select o;
if(!objQry.Any())
{
return null;
}
The whereConditions variable is a string I build and pass as parameter to find out the values I need. Here's examples of valid string:
OBJ_NAME == \"Sword\" and OBJ_OWNER == \"Stan\"
This will return any item whose name is "Sword" and owner is "Stan;
OBJ_COLOR == \"Blue\" OR OBJ_COLOR == \"Red\"
This will return any item which color is either blue or red.
Up to there, I'm fine, but now I have a problem: I need to check a decimal field. So I've tried this string:
OBJ_NUMBER == 1
But the query returns null even if there are objects which OBJ_NUMBER value is 1. It's a decimal. How can I indicate the query that they need to check for a decimal value?
**** EDIT ****
I have tried to "modify" the value passed so that it looks like this:
"CARD_NUMBER == Convert.ToDecimal(1)"
And now I have a different kind of error telling me this:
LINQ to Entities does not recognize the method 'System.Decimal ToDecimal(Int32)' method, and this method cannot be translated into a store expression.
Any clues anyone? I'm still looking for a way to do this. Thanks!
EDIT 2
You can get an example of how my code is shaped by looking at this question.
Let's come back at this problem. I want to check decimal values. Let's say that OBJ_NUMBER is a decimal field.
Using Dynamic Linq, I tried to read the decimal field. Say that I want to get each object which number is 1.27. The whereConditions field would then be shaped like this:
OBJ_NUMBER == 1.27
But then I would get an Invalid real literal '1.27' error. I don't know why.
So I have tried Gert Arnold's solution and done this instead:
decimal bDecimal = decimal.Parce(valueToParse);
param = new ObjectParameter("cardNumber", typeof(decimal)) { Value = bDecimal };
valuesToUse.Add("CARD_NUMBER == #cardNumber");
listParams.Add(param);
But I ended up having 2 problems:
The first problem is that my whereConditions string is shaped this way:
CARD_NUMBER == #cardNumber
But I get the following error:
No property or field 'cardNumber' exists in type 'CARD'
Leading me to believe that it cannot make the link between the object parameter and the string used to do the query.
As you can see, I have a list of Params. This is because I cannot know for sure how many parameters the user will chose. So each time the user enters a new search field, I have to create a new ObjectParameter and store it in a list. Here's how I try to do the thing after:
ObjectParameter[] arrayParameters = listParams.ToArray();
// Convert the list to an array
And then, when I try to make the query:
cardQry = from c in mDb.CARD.Where(whereConditions, arrayParameters)
select c;
But to no avail.
RESULTS
Based on the answered question below, I have developped something "awful", yet functional.
First of all, I ignore every decimal fields because I could never reach them with dynamic linq. Instead, I do this:
var valuesToParse = keyValuePair.Value.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
// Here I parse the value and, if that's the case, the symbol.
decimal baseValue = decimal.Parse(valuesToParse[0]);
if (valuesToParse.Count() > 1)
{
string baseMethod = valuesToParse[1];
if (baseMethod == ">" || baseMethod == ">=")
{
if (baseMethod == ">=")
{
baseValue--;
}
// The list is actually like this: Dictionary<string, object> list = new Dictionary<string, object>();
list.Add("low", baseValue);
// I kind of activate a tag telling me that the user is looking for a higher value.
cardHigher = true;
}
else
{
if (baseMethod == "<=")
{
baseValue++;
}
list.Add("low", baseValue);
cardLower = true;
}
}
else
{
//lowParam = new ObjectParameter("dec", typeof(decimal)) { Value = baseValue };
list.Add("low", baseValue);
}
cardNumberActivated = true;
At the end, when I get the list of objects, I do this:
if (list.Count > 0)
{
(example)
if (cardNumberActivated)
{
if (cardHigher)
{
q = mDb.CARD.Where("CARD_NUMBER >= #0", list["low"]).ToList();
}
else if (cardLower)
{
q = mDb.CARD.Where("CARD_NUMBER <= #0", list["low"]).ToList();
}
else
{
q = mDb.CARD.Where("CARD_NUMBER == #0", list["low"]).ToList();
}
}
}
// Here we get the orinalData with the basic filters.
listToReturn.AddRange(cardQry);
if (q != null)
{
//listToReturn.AddRange(q);
for (int i = 0; i < listToReturn.Count; i++)
{
var priceList1 = listToReturn[i];
if (!q.Any(_item => _item.CARD_NUMBER == priceList1.CARD_NUMBER))
{
listToReturn.RemoveAt(i);
i--;
}
}
}
And it works. This is not an elegant way to make it work, but I can validate the fields the way I wanted, and for this, I am thankful at last.
You should not build a query string with inline predicate values. Use parameters in stead. Then will also be able to specify the type:
var whereConditions= "it.CARD_NUMBER = #cardNumber";
var param = new ObjectParameter("cardNumber", typeof(decimal)) { Value = 1 };
objQry = from o in m_Db.OBJECTS.Where(whereConditions, param);
Edit
I don't know what doesn't work in your code. Here's just a random piece of working code derived from one of my own projects:
var param1 = new ObjectParameter("dec", typeof(decimal)) { Value = 90000m };
var param2 = new ObjectParameter("int", typeof(int)) { Value = 90000 };
var q = ValueHolders.Where("it.DecimalValue >= #dec OR it.IntegerValue > #int",
param1, param2).ToList();
Note that param1, param2 could also be an array of ObjectParameter.