i have mysql query which return some data with dates. When i am requesting ajax request it add timestamp into my response.
Is there any way so it didn't added timestamp automatically on responses.
jQuery.ajax({
url: "/getdata",
type: "POST",
data: { },
success: function (result, textStatus, jqXHR) {
console.log(result)
}
});
var query = "SELECT SUM(`id`) as `total`,DATE(`log_date`) as `log_date` from `mytable` Group by `log_date`"
This is my response which is adding T18:30:00.000Z to end of the dates:
[
RowDataPacket { total: 1, log_date: 2020-11-09T18:30:00.000Z },
RowDataPacket { total: 10, log_date: 2020-11-10T18:30:00.000Z },
]
Thanks
This isn't a jQuery issue, it's a mix of JS and PHP and how you're storing your date values in the database.
JS Date objects have to contain a time value as well. There is no date-only data type. As such your response from PHP is interpreted with the date you return and a time of 00:00:00 is added to it to maintain validity.
I can see from your profile that you are in India so your timezone offset is +5:30, hence JS assumes the date is in your local format and tries to convert it to UTC by subtracting 5:30 from it. Therefore the resulting date is 1 day before the actual value at 16:30:00.
To fix this I would suggest you return your dates in full ISO8601 format, including time and offset, so there is no ambiguity that JS attempts to overcome.
Related
I make a bot which is connected with spreadsheets with Webhook.
I have a cell with a date formatted like 'dd MMMM', e.g. "03 september". It is got from a certain amount of milliseconds which is equal to 03.09.2020 00:00:00 GMT+3.
I want to use this exact value ("03 september") as a poll option.
You can see my code below.
If I use it as it is, poll option is somehow converted into the value
"2020-09-02T21:00:00.000". If I map all the dates into Strings before sending it into JSON then this option looks like "Thu Sep 03 2020 00:00:00 GMT+0300 ... ".
How can I keep it looking simple in telegram?
UPD: I figured that Utilities.formatDate() is a proper solution for this, but still I don't know how to format month name into russian locale.
function doWork() {
var availableDates = scheduleSheet.getRange(1, 1, 1, 5).getValues()[0];
//var stringDates = availableDates.map(function(date) {return String(date)});
sendPoll(chatId, availableDates);
}
function sendPoll(chatId, options) {
var data = {
method: "post",
payload: {
method: "sendPoll",
chat_id: String(chatId),
question: "Some question:",
options: JSON.stringify(options),
is_anonymous: false,
allows_multiple_answers: true,
reply_markup: JSON.stringify(REMOVE_KEYBOARD)
}
};
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);
}
Posting this for documentation purposes.
As Tanaike suggested, in order to keep the displayed formats when retrieving dates (or any value) from sheet cells in Apps Script, use getDisplayValues() instead of getValues():
Returns a two-dimensional array of displayed values, indexed by row, then by column. The values are String objects. The displayed value takes into account date, time and currency formatting, including formats applied automatically by the spreadsheet's locale setting.
In my flutter app, I have a funtion that sends an ISO date string to a node.js rest API. However, when the date is parsed with in the js Date object, it returns a different date. I've also tried to send it in other formats like .toLocal() and .toUtc() with the same result.
Flutter (Dart)
///
/// SEND DATE TO NODE.JS ENDPOINT
///
void sendDate() async {
DateTime date = new DateTime(2020, 1, 1);
http.Response response = await http.post(
Uri.encodeFull('${config.domain}/sendDate'),
headers: { "Content-type" : "application/json"},
body: jsonEncode({"date": date.toIso8601String()})
);
print("Sent date");
print(date.toIso8601String());
print("Received date");
print(response.body);
}
Output
I/flutter (14203): Sent date
I/flutter (14203): "2020-01-01 00:00:00.000"
I/flutter (14203): Received date
I/flutter (14203): "2019-12-31T23:00:00.000Z"
Node.js (Javascript)
api.post('/sendDate',(req,res)=>{
console.log("Sent date")
console.log(req.body.date)
const date = new Date(req.body.date);
console.log("Parsed date");
console.log(date);
res.send(date);
});
Output
Sent date
2020-01-01T00:00:00.000
Parsed date
2019-12-31T23:00:00.000Z
As shown above, the date parsed by Javascript is one day less than the date sent by flutter.
P.S: As stated above, i've sent it in other formates like locale and UTC. Also no timezone configuration has been added.
EDIT: The date returned is actually an hour less. i.e sending DateTime(2020, 1, 1, [2]), will return DateTime(2020, 1, 1, [1]).
According to JavaScript's only in-spec date/time format, the string "2020-01-01 00:00:00.000" is invalid (it should have a T, not a space, between the date and time). (Indeed, according to Wikipedia, a space isn't valid in ISO-8601, either, though it's a common implementation extension.) But V8 (the JavaScript engine used by Node.js) is okay with that, it'll handle a space instead.
Additionally, the string has no timezone information, so this part of the date/time string parsing rules kicks in:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
So you appear to be in a timezone that's at GMT+0100. Midnight on Jan 1st in Europe, West Africa, etc. (GMT+0100) is 11 p.m. Dec 31st UTC / GMT.
If you want that date/time interpreted as UTC, you need to add a Z to the end before parsing. To be completely within spec, replace the space with a T as well.
Consider the following dummy code in a JavaScript file in an ASP.Net MVC5 Project.
var $grid = $("#grid")
var postData = $grid.jqGrid("getGridParam", "postData");
postData["xyzId"] = $("#xyzId").val();
postData["date"] = $("#date").val();
$grid.setGridParam({ postData: postData });
$grid.setGridParam({ datatype: "json", page: 1 }).trigger("reloadGrid");
Following is the Controller's ActionMethod where the request arrives...
public ActionResult GetXyz(int xyzId, DateTime? date)
Keeping the date nullable is the need because it is an optional selection.
PROBLEM:
The date format in Culture settings of .Net Framework is "DD/MM/YYYY" and when we send "02/10/2016" it accepts as "February 10, 2016" (which is wrong btw) but when we send "16/10/2016" it reads it as null. This is only happening when we are passing dates in jqGrid Reload operation. Whereas, in normal ajax call, everythins is working well
e.g. "02/10/2016" => "October 02, 2016",
and "16/10/2016" => "October 16, 2016".
Can anyone help?
It's recommended to use only locale independent formats to transfer the data. It's common rule for numbers, date, ... You can convert $("#date").val() to the format YYYY-MM-DD (ISO 8601 format of date) before assigning to postData.xyzId? I think that ISO date format is default for Newtonsoft.Json used in MVC.
Typically one use formatter: "date" with optional formatoptions with newformat property. In the way you hold internally and transfer only locale independent data, but the user will see local specific dates (based on formatoptions.newformat which you specify explicitly in colModel or the implicit value inherited from grid.locale-XX.js).
Catch the date as string
public ActionResult GetXyz(int xyzId, string date="")
and then format it in conventional way:
var Date= DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Hope this will help :)
Our previous developer create a generic method that retrieve all user input that has an update/changes.
it looks like this (user side/JavaScript/Kendo):
param._updated = JSON.stringify(rows._updated);
I am somehow desperate that when that *rows._updated contains a Date Value uncle JSON convert it into other String format that result to DateTime Difference for example:
dateField = 11/1/2015 // <--Original User Input
rows._updated = { dateField: November 1, 2015 0:00:00 GMT+080 ... }
param._updated = { "dateField": "2015-10-31T16:00:00.0000Z"... }
which would now result to a conflict.
since the above code was generic field that might contain different data and type, I am trying to solve this issues at the server side but i failed to achieve the original date value.
NOTE: our users has 2-5 different timezone so it's kinda hard to hard code the conversion.
related issues: here
It's getting late. Thanks in advance!.
I somehow achieve what I want to by the following approach
1.) At backend Convert the DateTime to UTC Format
string dateUTC = paramDate.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
2.) Now I have created a method that will handle the convertion of UTC Date to PlainDate
public static string UTCtoPlainDate(string dateUTC)
{
if (string.IsNullOrEmpty(dateUTC)) return "";
DateTime dateTime;
// Assume date in UTC format, e.g. '2015-03-31T12:00:00.000Z'
DateTime.TryParseExact(dateUTC, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out dateTime);
return dateTime.ToString("yyyy-MM-dd") ?? "";
}
I am new to Postgresql and I am using WCF services.
Here is my code snippet:
$.ajax({
url: '../Services/AuctionEntryServices.svc/InsertAuctionDetails',
data: JSON.stringify({ "objAuctionEntryEntity": {
"AuctionNO": '',
"AuctionDate": $('[Id$="lblAuctionDateVal"]').text(),
"TraderID": $('[Id$="ddlTraderName"] option:selected').val(),
"Grade": $('[Id$="ddlGrade"] option:selected').val(),
"Varity": $('[Id$="ddlVarity"] option:selected').val(),
"QuntityInAuction": $('#txtQuantityForAuction').val(),
"AuctionRate": $('#txtAuctionRate').val(),
"BrokerID": a[0],
"IsSold": $('#chlIsSold').is(':checked'),
"CreatedBy": $.parseJSON(GetCookie('Admin_User_In_Mandi')).UserID,
"UpdatedBy": $.parseJSON(GetCookie('Admin_User_In_Mandi')).UserID,
"CreationDate": GetCurrentDate().toMSJSON(),
"IsActive": true,
"AuctionTransaction": arrAuctionTransaction,
"MandiID": $.parseJSON(GetCookie('Admin_User_In_Mandi')).MandiID,
"FarmerID": _ownerid,
"AuctionNO": _auctionno,
"AmmanatPattiID": _ammantpattiid,
"ToTraderID": b[0],
"ToTraderName": $('#txtOtherBuyerNameEN').val(),
"ToTraderName_HI": $('#txtOtherBuyerNameHI').val()
}
}),
type: 'POST',
contentType: 'application/json',
dataType: 'json'
});
Here:
$('[Id$="lblAuctionDateVal"]').text() = "20/8/2013 14:52:49"
And my data type for this field is timestamp without time zone.
How to convert this string to timestamp without time zone data type?
String representation of a timestamp (= timestamp without time zone) depends on your locale settings. Therefore, to avoid ambiguities leading to data errors or Postgres coughing up an exception, you have two options:
1.) Use ISO 8601 format, which works the same with any locale or DateStyle setting:
'2013-08-20 14:52:49'
You may have to cast the string literal explicitly where the data type cannot be derived from context, depending on the use case:
'2013-08-20 14:52:49'::timestamp
2.) Convert the string to timestamp using to_timestamp() with a matching template pattern:
to_timestamp('20/8/2013 14:52:49', 'DD/MM/YYYY hh24:mi:ss')
This returns timestamptz, assuming the current timezone setting. Typically (like in an assigmment) the type is coerced accordingly. For timestamp, this means that the time offset is truncated and you get the expected value.
Again, if the target type cannot be derived from context, you may have to cast explicitly:
to_timestamp('20/8/2013 14:52:49', 'DD/MM/YYYY hh24:mi:ss')::timestamp
Since that simply strips the time offset, it results in the expected value. Or use the AT TIME ZONE construct with a time zone of your choosing:
to_timestamp('20/8/2013 14:52:49', 'DD/MM/YYYY hh24:mi:ss') AT TIME ZONE 'UTC'
While the target time zone is the same as your current timezone setting, no transformation takes place. Else the resulting timestamp is transposed accordingly. Further reading:
Ignoring time zones altogether in Rails and PostgreSQL
To convert a string into a timestamp without timezone, for Postgresql, I use the above
SELECT to_timestamp('23-11-1986 09:30:00', 'DD-MM-YYYY hh24:mi:ss')::timestamp without time zone;