How to parse a Javascript datetime to C# DateTime parameter - javascript

According to my previous question here: How to send a JSON object using GET method, I could retrieve my values because the object is no longer null. My object contains one DateTime property called CreatedOn. I am sending the value from javascript as new Date(). Before to answer that I can get the DateTime.Now() from code-behind, there is a purpose to send the date from HTML.
Then, in debug mode when I arrive to the controller method, my CreatedOn property is always DateTime.MinValue = 01/01/0001 12:00:00 AM
I changed my javascript value to this format "yyyyMMddT000000" because I thought that this would be parsed automatically but I didn't have any success.
How can I do to send the value that can be parsed by the web api2 controller automatically?
<script>
$("#btnTest").on("click", function () {
var searchCriteria = {};
searchCriteria.ID = 0;
searchCriteria.Name = "";
//1. First tried option
//searchCriteria.CreatedOn = new Date();
//2. Second tried option. Test
searchCriteria.CreatedOn = "20170324T000000";
var url = "http://localhost:8080/api/products"
$.getJSON(url, searchCriteria).done(processResponse);
});
function processResponse(response){
}
</script>

I got it. Hope this can help others.
searchCriteria.CreatedOn = new Date().toISOString();
This will be parsed automatically.
Cheers.

Related

How can I get date and time separately using jQuery?

In my table date is listed as "2015-07-31 06:02:20". How can I get date and time separately using jQuery?
I used some code but it shows some errors.
var timestamp = new Date(data.responsecusthistory.created_at);
var date = timestamp.toDateString();
Error: Invalid Date
var date = data.responsecusthistory.created_at.split(" ")[0];
var time = data.responsecusthistory.created_at.split(" ")[1];
If you want to have a time string (i.e. HH:MM:SS), try e.g. this:
var timestampTime = timestamp.toTimeString().split(' ')[0];
Anyway, there's no obvious reason why you get the "Error: Invalid Date", as long as
data.responsecusthistory.created_at
is a correct value, such as "2015-07-31 06:02:20". Please consider double-checking this variable.
Try this:
dateString= "2015-07-31 06:02:20";
temp = new Date(dateString);
dateStr= $.datepicker.formatDate('mm/dd/yy', temp );
for getting different formats check the link https://github.com/phstc/jquery-dateFormat.
Using different formats we will get different date, time etc in which ever forms we need it.

MomentJS how to get formatted, but not localised representation?

I'm using MomentJS v2.8.4, and I'm trying to get formatted date like "31/12/2015"
myDate.format('DD/MM/YYYY') works fine until I set some "less English :)" localisation, e.g. Arabic. Then I get something like this ١٠/٠١/٢٠١٥, which is nice for the user, not so nice for API.
From MomentJS source code
format : function (inputString) {
var output = formatMoment(this, inputString || moment.defaultFormat);
// here I get correct "31/12/2015" format
return this.localeData().postformat(output); // this will return localized version
},
formatMoment function is not publicly exported...
Can you please suggest correct solution for this?
You could save the current locale() setting in a variable (i.e save the user's setting) and then explicitly set the locale value so that you can get your date format correct for your API call, then set the locale value back to the saved value.
Something like:
var userLocaleSetting = moment.locale();
moment.locale('en');
var myFormattedDate = myDate.format('DD/MM/YYYY');
moment.locale( userLocaleSetting );
One solution may be to return an object with the api and user formatted date.
format : function (inputString) {
var api = formatMoment(this, inputString || moment.defaultFormat);
// here I get correct "31/12/2015" format
var user = this.localeData().postformat(api); // this will return localized version
return {api: api, user: user};
},

How could I parse this date value transferred from model to javascript?

var time =<%:Html.Raw(Json.Encode(Model.AvailableDates))%>;
var parsed = time[0];
alert( parsed );
The pop up shows: "/Date(1174021200000)/". It is not a instance of date. I tried .toString("mm/dd/yy"), Date.parse(parsed), new Date(parsed). Unfortunately, none of these works. I dont wanna let my controller return a formatted value. Is there a way I can parse it on client side? thank you. By the way AvailableDates is a list of datetime in c#.
you can parse it like this:
var date = new Date(<% Model.AvailableDates %>);
Try use moment.js
var time =<%:Html.Raw(Json.Encode(Model.AvailableDates))%>;
var parsed = moment(time);
alert( parsed );
See an example here in jsfiddle

Deserializing JSON dates timezone-less

I have a problem that is breaking my head since yesterday and don't know how to deal with it.
I have a date field in my database that contains the following value:
Then my application get the value and send that to my web form. (the value still the same :) thats fine!!
In client side I put a break with a javascript alert to see the value that is comming from JSON (the value still the same :) thats fine!!
The code in client side for the alert is this:
// transaction json model
var jsonTransaction = #(Html.Raw(Json.Encode(this.Model.Transaction)));
alert(new Date(parseInt(jsonTransaction.Date.substr(6))));
Now when I send back the value to the server this is what I get
And finally after deserialization of the JSON my date time is wrong!! instead of Day 7 its now Day 8???????
This is the code for deserializing:
public JsonResult SaveBill(string jsonTransaction, string jsonTranDetails)
{
_appState = this.AppState;
JsonResult returnVal = returnVal = Json(
new { Success = true }
);
var transaction = JsonConvert.DeserializeObject<BillTransaction>(jsonTransaction, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
Any clue on how to solve this issue with dates, I should get the same date because I didn't change anything. Hope someone can guide me for a solution.
Thanks in advance.
Java script use universal time when it parse the date as currentdate = new Date(123232)
so when you send date to client convert it to ISO date such as
make sure the date is in UTC before convering it to strong .
return String.Format("{0:yyyy-MM-ddTHH:mm:ss.fffZ}", dt);
bty I already created JSON Converted to override any date serialization to client side to use the above function .

Getting value of field with Javascript/jQuery

This is my page:
http://bryntum.com/examples/gantt-latest/examples/basic/basic.html
I want to get current value of Start and Finish date.
( I will later implement a button, that user can press and then it will get all dates and post them somewhere). At the moment I just need somehow to get the date values.
At first the values are loaded from XML, but you can change the values manually.
I tried looking into source code, but was not able to get the field IDs etc.
So how I can access those fields with JS?
In case you're still looking for JS solution:
I couln't use Jquery, does the server support it?
By using JS, since the cells do not have an ID, you can access your fields by class name:
document.getElementsByClassName("x-grid-cell-inner ");
And than iterating trough the returned array.
Complete code:
var data = document.getElementsByClassName("x-grid-cell-inner ");
var mark = 0;
var out = "";
var patt=/\d\/\d/;
for (i in data) {
var txt = new String(data[i].innerHTML);
if (patt.test(txt)) {
if (mark == 0) {
out += "start: "+txt+" ";
mark = 1;
} else {
mark = 0;
out += "end: "+txt+" ";
}
}
}
It would be totally wrong to do this with jquery - It's an Extjs component with really good documentation.
Gnt.panel.Gantt has a getStart method:
Method to get a the current start date of the scheduler view
and a getEnd method:
Method to get a the current end date of the scheduler view
http://bryntum.com/docs/#!/api/Gnt.panel.Gantt
Edit:
Try getTaskStore, then getById on the store witch will return a Task that has a StartDate and EndDate fields.
unfortunately, there's no unique id on the divs so you can't access them. but they seem to have unique class="" values:
class="x-grid-cell x-grid-cell-startdatecolumn-1011"
class="x-grid-cell x-grid-cell-enddatecolumn-1014"
create a javascript like this
document.getElementsByClassName("x-grid-cell x-grid-cell-enddatecolumn-1014")
to access them and then you can get their start and end dates

Categories

Resources