I have a MVC Web Application Im trying to Ajax call an action method to retrieve some datetime from the database, the problem is the value comes as "/Date(386028000000)/"
its a DateOfBirth actually which I m using a java script function to calculate the age:
function (DOB) {
var birthday = +new Date(DOB);
return ~~((Date.now() - birthday) / (31557600000));
}
Anyway i can fix the Date Format and get only the date in a proper format or change the Java-Script method to accept the current format of the date value ?
I got it
var FixedDate = new Date();
FixedDate .setTime(DOB.replace("/Date(", "").replace(")/", ""));
return ~~((Date.now() - FixedDate) / (31557600000));
Click here to check the Demo
Sample Javascript/JQuery
var = MyDate_String_Value = "/Date(386028000000)/"
var value = new Date
(
parseInt(MyDate_String_Value.replace(/(^.*\()|([+-].*$)/g, ''))
);
var dat = value.getMonth() +
1 +
"/" +
value.getDate() +
"/" +
value.getFullYear();
Result - "3/27/1982"
Related
function doGet(e){
Logger.log("--- doGet ---");
var tag = "",
value = "";
try {
// this helps during debuggin
if (e == null){e={}; e.parameters = {tag:"test",value:"-1"};}
tag = e.parameters.tag;
value = e.parameters.value;
// save the data to spreadsheet
save_data(tag, value);
return ContentService.createTextOutput("Wrote:\n tag: " + tag + "\n value: " + value);
} catch(error) {
Logger.log(error);
return ContentService.createTextOutput("oops...." + error.message
+ "\n" + new Date()
+ "\ntag: " + tag +
+ "\nvalue: " + value);
}
}
// Method to save given data to a sheet
function save_data(tag, value){
Logger.log("--- save_data ---");
try {
var dateTime = new Date();
// Paste the URL of the Google Sheets starting from https thru /edit
// For e.g.: https://docs.google.com/..../edit
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1HYJRHfJVgZp16xYt4fipR1bH2BudhuQ4UrDhAf1rBKw/edit");
var dataLoggerSheet = ss.getSheetByName("Datalogger");
// Get last edited row from DataLogger sheet
var row = dataLoggerSheet.getLastRow() + 1;
// Start Populating the data
dataLoggerSheet.getRange("A" + row).setValue(row -1); // ID
dataLoggerSheet.getRange("B" + row).setValue(dateTime); // dateTime
dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
dataLoggerSheet.getRange("D" + row).setValue(value); // value
//dataLoggerSheet.getRange("E" + row).setValue(value); // value
//dataLoggerSheet.getRange("F" + row).setValue(value); // value
// Update summary sheet
summarySheet.getRange("B1").setValue(dateTime); // Last modified date
// summarySheet.getRange("B2").setValue(row - 1); // Count
}
catch(error) {
Logger.log(JSON.stringify(error));
}
Logger.log("--- save_data end---");
}
In the example above, inside the value of "tag" there is data in the format "12345678912 | ABCDEFGHIJ". "Tag" data in column C; I want to print with the first 11 characters in column D. The "tag" data in column C; I want to print it with column E after 12 characters. How can I do that?
To see my overall objective, these two screenshots should show it.
Original Spreadsheet from Form:
enter image description here
Formatted Version of Spreadsheet:
enter image description here
Thank you in advance for your help.
You will have to manipulate the tag string in order to get the values you want.
In order to do this you will have change this:
dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
To this:
dataLoggerSheet.getRange("C" + row).setValue(tag.slice(0,tag.indexOf('|')); //first part of tag
dataLoggerSheet.getRange("D" + row).setValue(tag.slice(tag.indexOf('|') + 2)); // second part of tag
dataLoggerSheet.getRange("E" + row).setValue(value); // value
Explanation
The above snippet makes use of the indexOf and slice methods from JavaScript in order to get the index of the | character in order to be able to split the tag string into two different strings.
Reference
JavaScript Array.prototype.slice();
JavaScript Array.prototype.indexOf().
I'm trying to use the Kendo UI MVC dateTimePicker to format the date unambiguously so that MVC model binding understands it. I have a datetimepicker control in a form which submits via a GET request.
MVC expects dates in this format: yyyy-MM-dd but I want to display dates on the page as dd/MM/yyyy
If I use this code, MVC parses the date correctly, but displays the year first to the user, which isn't what I want:
#(Html.Kendo().DateTimePicker()
.Name("ToDate")
.Format("yyyy-MM-dd")
)
Is there a workaround so I can format the date for humans in the box, but format it in an unambiguous (invariant) format in the URL?
You should configure your DateTimePicker format to a user friendly format. Then use javascript to get the Date object from the widget (not string date). Then format this date object to 'yyyy-mm-dd' and make the request.
So your widget shoul be:
#(Html.Kendo().DateTimePicker()
.Name("ToDate")
.Format("dd/MM/yyyy")
)
Then use this javascript to make the request:
var date = $("#ToDate").data("kendoDateTimePicker").value();
date variable have a javascript date you can format:
function dateToString(date){
var str = date.getFullYear() + "-";
str += ('0' + (date.getMonth() + 1)).slice(-2) + "-";
str += ('0' + date.getDate()).slice(-2) + "T";
str += ('0' + date.getHours()).slice(-2) + "-";
str += ('0' + date.getMinutes()).slice(-2) + "-";
str += ('0' + date.getSeconds()).slice(-2);
return str;
}
This format is "yyyy-mm-dd hh:mm:ss", but you can remove the time part if you want
I am trying to make a custom publish date, because the user wants to use that as the publishing date and for sorting. The date will also be displayed on the page.
Here is what I want:
The user can input a date
The date can be empty (meaning it will be published now)
It has to use that date for sorting
The date has to be set to UTC time, so it's equal for everyone in the world
I am desperate and I cannot figure out how to do this.
Here is what I have tried so far: I found a neat little plugin, which displays the user's current UTC time next to the input field, so the person knows their UTC time. I modified that to always enter the current date in the input field:
var timer = setInterval(function () {
var date = $(".custom-date").val();
if (date === "") {
$(".custom-date").focus();
$(".custom-date").click();
$(".custom-date").trigger("click");
//the date has now been set on the input field
} else if (date !== "") {
var newDate = new Date(date);
var stringDate = newDate.getFullYear() + "-" + ('0' + (newDate.getMonth() + 1)).slice(-2) + "-" + ('0' + (newDate.getDate() - 1)).slice(-2) + " " + ('0' + (newDate.getHours() - offset)).slice(-2) + ":" + ('0' + newDate.getMinutes()).slice(-2) + ":" + ('0' + newDate.getSeconds()).slice(-2);
$(".custom-date").val(stringDate);
angular.element(".custom-date").scope().$apply(function () {
angular.element(".custom-date").scope().datetimePickerValue = stringDate;
});
clearInterval(timer);
}
}, 1000);
Yes, this looks like a lot... and no, it does not work. I do the focus/click/trigger on the element, because that will automatically set the time to be the user's local time. I then turn that into UTC time (offset is the UTC time offset). Then I apply the date to the element's scope and the value gets updated both in $scope and in the view (I can actually see it).
However, when I hit save and publish, the date gets reset (it's empty in the database). It's only when I physically click on the input field and select a new date it will actually update it. I like this method, as I am in 100% control of it, so is it possible? It would seem like setting the new date on the scope doesn't trigger the actual "new date has been selected".
Alternatively I have my Razor code here:
//selection is all my elements/nodes
selection.OrderByDescending(x => x.GetProperty("publishDate") != null).ThenByDescending(x => x.GetPropertyValue("publishDate")).Where(x => x.GetPropertyValue<DateTime>("publishDate") < DateTime.UtcNow);
So apparently before the Angular event is triggered, I need to, at least, call these:
$(".custom-date").trigger("click");
$(".custom-date").change();
So I did that right after I set my new date and now it works.
Is there a way to get the cookie,set in JavaScript code, inside a controller method in Ruby on Rails v 4.0 ?
In a controller, you can set a cookie with:
cookies['foo'] = 'bar'
To set a cookie in Javascript, I wrote a short function in Coffeescript:
set_cookie: ( name, value, expiredays = 0 ) ->
expiredate = new Date()
expiredate.setDate expiredate.getDate() + expiredays
expire = '; expires=' + expiredate.toUTCString()
value = escape( value ) + expire
document.cookie = name + '=' + value + '; path=/'
I have a view that accepts 2 string parameters and 2 date values. User hits search button and they get filtered output to the screen. This all works perfectly well until a user inputs a string with a space. i.e. they can search for 'waste' but not 'waste oil'.
Interestingly, in the latter, the parameter is ok from Javascript before the call is made. But on entering the controller code it goes form being 'waste oil' on client to 'waste'. When this happens the other parameters get set to NULL crashing the system.
I've tried replacing the spaces if present with '#' character then stripping out and putting back in ' ' on the controller side. This is a messy fudge and only appears to work with one parameter.
There must be a simple explanation for this parameter data loss, any comments much appreciated
Not sure a code example is needed but here it is anyway if it help:
My controller header :
public ActionResult IndexSearch(int? page, string searchText,string searchTextSite,string StartDate,string EndDate)
{
My HTML Javascript :
function Search(sSearchText,sSite) {
sSearchText = sSearchText.toString().replace(" ", "#");
sSite = sSite.toString().replace(" ", "#");
debugger;
alert($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val());
$("#ResultsList").load($("#AbsolutePath").val() + "Waste.mvc/IndexSearch?searchText=" + sSearchText + "&searchTextSite=" + sSite + "&StartDate=" + $('#StartDate').val() + "&EndDate=" + $('#EndDate').val(),
function() {
$('#LoadingGif').empty();
});
$('#LoadingGif').empty().html('<img src="' + $("#AbsolutePath").val() + 'Content/images/ajax-loader.gif" alt="Loading image" />');
}
You are not URL encoding your parameters when sending the AJAX request because you are using string concatenations when building the url. You could use the following technique in order to have properly encoded values:
var url = $('#AbsolutePath').val() + 'Waste.mvc/IndexSearch';
var data = {
searchText: sSearchText,
searchTextSite: sSite ,
StartDate: $('#StartDate').val(),
EndDate: $('#EndDate').val()
};
$('#ResultsList').load(url, data, function() {
$('#LoadingGif').empty();
});
Now you will get correct values on the server.