net core 3.1 mvc web app. On my server I do:
[HttpGet]
public IActionResult LastDate()
{
DateTime send = DateTime.Now;
try
{
send = _db.MySend.ToList().Max(x => x.Date).GetValueOrDefault().AddDays(1);
}
catch { }
return Json( new { date = send });
}
then on my Front-end I do:
var link = 'MYLINK';
var args = {};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
var my_date = data.date;
document.getElementById('Dateee').value = my_date;
},
error: function () {
alert("Error.");
return;
}
});
I have tried to convert Json date to Javascript but I am unable. Thanks for any help.
EDIT: 1. I am using Microsoft.AspNetCore.Mvc Json.
2. My localization that affects date:
var supportedCultures = new[]{
new CultureInfo("cs-CZ")
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("cs-CZ"),
SupportedCultures = supportedCultures,
FallBackToParentCultures = false
});
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("cs-CZ");```
The JSON specification does not prescribe any particular representation for date+time values (annoyingly...).
So there are a variety of formats and approaches for sending .NET DateTime and JS Date values via JSON.
Such as sending the UNIX time in milliseconds.
Or sending an ISO 8601-formatted string
Or the horrible format that ASP.NET AJAX used between 2005 and ~2012 that looked like "/Date(12345)/" (what on earth where they thinking?!).
Absent any further information in your post, I recommend serializing the value using an ISO 8601 string, which has the advantage of being compatible with HTML5's <input type="date" /> via the Date constructor and the valueAsDate property.
While we're at it, let's make your controller action async (as it looks like you're using Entity Framework).
And let's make your client-side code use async fetch.
PLEASE EVERYONE STOP USING JQUERY IT'S 2020 FOR TIM BERNERS-LEE'S SAKE STOP USING IRRELEVANT AND OBSOLETE CLIENT-SIDE LIBRARIES FROM 10 YEARS AGO AIAIIEIEIEIEIEIIE
Like so:
[HttpGet]
public async Task<IActionResult> LastDate()
{
DateTime value = await this._db.MySend.MaxAsync( x => x.Date );
DateTime send = value.AddDays(1);
String formatted = send.ToString( "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture );
return this.Json( new { date = formatted } );
}
Client-side:
try {
const resp = await fetch( link );
if( resp.status === 200 ) {
const obj = await resp.json();
const dateStr = obj.date; // string
const date = new Date( dateStr );
document.getElementById('Dateee').valueAsDate = date;
}
}
catch( err ) {
alert( "Error: " + err );
}
Related
I am new to sorting or filtering data in Spring Boot and want to fetch all order records between two dates when selected from UI.
I have created REST API to search data between two dates, but even when I am providing wrong dates, I am getting data.
To display table, I have implemented it through Pagination.
So when I select two dates in which data is present and click on button, then it will display fetched data in a table.
But this is not working as expected and I do not know where I am doing wrong.
For example: I have selected fromdate from UI as: 01-06-2021 and todate from UI as: 04-06-2021 and clicked on fetch record button, then records should be displayed according to date range. Suppose If I select fromdate: 14-06-2021 and todate as: 23-06-2021 (there is no records present between these two date ranges) still I am getting result from database.
Below is my Orders repository method to get data between date ranges.
List<Orders> findByOrderdateGreaterThanEqualAndOrderdateLessThanEqualAndOrderstatusOrderByCreateddatetimeDesc(Date fromdate, Date todate, String orderstatus);
Below is my controller where I have created API to fetch records between two dates:
#RequestMapping(value = AkApiUrl.fetchorderbydate, method = { RequestMethod.POST, RequestMethod.GET }, produces = {MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> fetchorderbydate(HttpServletRequest request, #RequestParam("startdate") String startdate, #RequestParam("enddate") String enddate) {
logger.info("Fetch order between start date: "+startdate+" and end date: "+enddate+" function is calling.. ");
CustomResponse = ResponseFactory.getResponse(request);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date orderdatefrom = sdf.parse(startdate);
System.out.println("Order placed from date: "+orderdatefrom.toString());
Date orderdateto = sdf.parse(enddate);
System.out.println("Order placed to date: "+orderdateto.toString());
List<Orders> orderbydate = ordersdao.findByOrderdateGreaterThanEqualAndOrderdateLessThanEqualAndOrderstatusOrderByCreateddatetimeDesc(orderdatefrom, orderdateto,"refunded");
System.out.println(orderdatefrom+" comes before"+orderdateto);
System.out.println("Order data between two dates are : "+orderbydate.size());
if (orderbydate != null) {
CustomResponse.setResponse(orderbydate);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
This is the script to handle fetch record between two dates and on ajax success another function is called to display table.
function getorderdata() {
debugger
var startdate = document.getElementById('orderstartdate').value;
var enddate = document.getElementById('orderenddate').value;
if ((Date.parse(enddate) >= Date.parse(startdate))) {
var url = "../api/fetchorderbydate";
$.post(url,{
startdate : startdate,
enddate : enddate,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
console.log(data.response);
ajaxordertable(<%=pagelength%>);
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
} else {
alert("End date should be greater than start date");
}
}
The fetched filtered-by-date data ought to be an input to the rendering function.
For example:
renderTable(data.response)
I am querying my database and returning a jsonresult, and using that to populate a grid, and I see that my date being returned is /Date(1507477743793)/. I have looked around and have seen solutions when it comes to converting one variable but not when it comes to an array of objects (I think thats right)
EDIT
Sample data
FileAReportID:1
ReportAddress:"1 Main Street West"
ReportDate:"/Date(1507477743793)/"
ReporterName:"Beetle Bailey"
This number 1507477743793 is the timestamp from your server. to conver this in other format just try this:
let t = (new Date(1507477743793)).toUTCString();
console.log(t)
// output
and you get: 2017/12/6 05:32:30pm
You can create custom jsonresult
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
Usage Example:
[HttpGet]
public ActionResult Index() {
return new CustomJsonResult { Data = new { } };
}
You can also create custom MediaTypeFormatter formatter and during serialization you can change the format of datetime.
Update
Json.Net supports multiple ways of formatting a date, if your consuming it from an ajax call you may want to look into JavaScriptDateTimeConverter.
Serializing Dates in JSON
I am working in ASP.NET MVC 5.
I am trying to deserialize dates coming from the server in JSON format. The JSON arrives and when I try to deserialize the dates the debugger just stops and don't show any errors other the in the console, which I can't understand.
This is my code so far:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '/Home/GetDates',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (dates) {
var date = dates[0];
var desDate = $.parseJSON(date, true);
console.log(desDate);
}
});
});
Here are some pics on the errormessage and that a have data coming in.
Here is a link to the docs I have been looking at. Docs
The data returned from the ajax call is already parsed, so dates is an array containing strings, and dates[0] is the string/Date(14984....)/ etc.
To parse the string, remove everything but the numbers, and use that timestamp to create a Date object.
$(document).ready(function () {
$.ajax({
type : 'GET',
url : '/Home/GetDates',
dataType : "json",
contentType : "application/json; charset=utf-8",
success: function (dates) {
var d = dates[0];
var unix = +d.replace(/\D/g, '');
var date = new Date(unix);
var desDate = date.getFullYear() + '/' +
(date.getMonth()+1) + '/' +
date.getDate();
console.log(desDate);
}
});
});
You need to execute the JavaScript inside your string variable as
var dateVar = eval(dates[0]);
This will give you the date but not in a proper format which you want. For the proper format user either moment.js or simply create your own lines of code like
var finalDate = new Date(dateVar).toISOString().split('T')[0];
console.log(finalDate);
The new Date() is again needed here so that we can make use of toISOString() and get the proper date format.
Because you are referring to this jQuery parseJSON automatic date conversion for Asp.net and ISO date strings you need to include the jQuery extension defined there.
Indeed, in jQuery parseJSON(jsonString) accepts only one argument while you are using an extension.
Moreover, your dates variable is an array of string, and not a json string.
//
// Look at the end....
//
/*
* jQuery.parseJSON() extension (supports ISO & Asp.net date conversion)
*
* Version 1.0 (13 Jan 2011)
*
* Copyright (c) 2011 Robert Koritnik
* Licensed under the terms of the MIT license
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
// JSON RegExp
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i;
var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i;
// replacer RegExp
var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z"/i;
var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i;
// determine JSON native support
var nativeJSON = (window.JSON && window.JSON.parse) ? true : false;
var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function (k, v) {
return "Y";
}) === "Y";
var jsonDateConverter = function (key, value) {
if (typeof(value) === "string") {
if (dateISO.test(value)) {
return new Date(value);
}
if (dateNet.test(value)) {
return new Date(parseInt(dateNet.exec(value)[1], 10));
}
}
return value;
};
$.extend({
parseJSON: function (data, convertDates) {
/// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary>
/// <param name="data" type="String">The JSON string to parse.</param>
/// <param name="convertDates" optional="true" type="Boolean">Set to true when you want ISO/Asp.net dates to be auto-converted to dates.</param>
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim(data);
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data
.replace(rvalidescape, "#")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
// Try to use the native JSON parser
if (extendedJSON || (nativeJSON && convertDates !== true)) {
return window.JSON.parse(data, convertDates === true ? jsonDateConverter : undefined);
}
else {
data = convertDates === true ?
data.replace(replaceISO, "new Date(parseInt('$1',10),parseInt('$2',10)-1,parseInt('$3',10),parseInt('$4',10),parseInt('$5',10),parseInt('$6',10),(function(s){return parseInt(s,10)||0;})('$7'))")
.replace(replaceNet, "new Date($1)") :
data;
return (new Function("return " + data))();
}
} else {
$.error("Invalid JSON: " + data);
}
}
});
})(jQuery);
var date = '{"date": "\\/Date(1498435200000)\\/"}';
var desDate = $.parseJSON(date, true);
console.log(desDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm modifying an ASP.NET project that I didn't worked on before.
I added a datepicker object :
<input id="datepicker" />
<script>
$("#datepicker").kendoDatePicker({
value: new Date()
change: UpdateVehiculesSurSite
});
</script>
And tried to modify the "UpdateVehiculesEnAttente" method to send the date picked to my controller :
function UpdateVehiculesEnAttente(){
var datepicker = $("#datepicker").data("kendoDatePicker");
console.log(typeof datepicker);
if (datepicker!==null && typeof datepicker !== "undefined"){
var value = datepicker.value();
console.log(value);
value = kendo.toString(value,"dd/MM/yyyy")
alert(value);
$(document).ready($.ajax({
url: 'Entrees_Sorties/Get_Vehicules_EnAttente',
type: 'POST',
data: {'date' : value},
contentType: 'application/json',
success: function (retour) {
$("#DivVehiculesEnAttente").html(retour);
console.log("update attente success");
},
error: function (xhr, status, error) {
montrerNotificationNoConnexion();
}
}));
//}
return false;
}
The first problem is that the project run the javascript file first, so the datepicker isn't initialized. To try my Controller method, I gave "value" a date.
My controller method is the following :
public ActionResult Get_Vehicules_EnAttente([DataSourceRequest] DataSourceRequest request, string date){
try{
List<List<Vehicule>> Data = new List<List<Vehicule>>();
DateTime dt = Convert.ToDateTime(date);
Data.Add(Models.Vehicule.Get_Vehicules_EnAttente_ByDate(dt, true));
return PartialView("VehiculesEnAttente", Data);
} catch (Exception e) {
WorkflowWCF.Log.enregistrer_erreur(new Exception("Une erreur est survenue lors de la récupération des véhicules planifiés", e));
return Json(new List<Vehicule>().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
}
The result is that my Ajax request return error and launch the "montrerNotificationNoConnexion" method.
Any idea why ?
EDIT :
Using Firebug, I get this
Do you think the problem could be that "date" contain "17%2F02%2F2016" instead of "17/02/2016" ?
EDIT2 : One of the problem was the string format. I changed it to "02/17/2016" but still not working.
You are defining your content type as contentType: 'application/json',
and then send data as simple text.
You should remove so that jquery uses the default 'application/x-www-form-urlencoded; charset=UTF-8' type.
You have to send the date in ISO 8601 format, then the MVC modelbinder can bind it.
var GlobalJsHelpers = GlobalJsHelpers || {};
/// <summary>
/// Takes a utc js date and converts it to a iso8601 utc string
/// </summary>
GlobalJsHelpers.Iso8601FromUtc = function(utcDate) {
//create a two digit month string (01-12)
var month = ('0' + (utcDate.getUTCMonth() + 1)).substr(-2);
//create a two digit day string (01-31)
var day = ('0' + utcDate.getUTCDate()).substr(-2);
return utcDate.getUTCFullYear() + '-' + month + '-' + day;
};
Usage:
data: {'date' : GlobalJsHelpers.Iso8601FromUtc(dateValueInUtc)}
I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .
I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?