Can I customize my AngularJS application to display local times? - angularjs

I am using an ASP.NET MVC / ASP.NET Web API back-end for my application. When a user updates data the time is recorded like this:
public HttpResponseMessage PutContent(int id, Content content)
{
if (id != content.ContentId)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
content.ModifiedDate = DateTime.Now;
content.ModifiedBy = User.Identity.GetUserId();
_uow.Contents.Update(content);
_uow.Commit();
return Request.CreateResponse(HttpStatusCode.OK, content);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
When the user looks at the modified time they see what I assume is the server time. Is there a way that I can allow them to see the local time that the change was made?
Note that already I do some formatting but I am not sure if there is a way that I can convert the date and have this matched up with my local users who could be in any location:
<input disabled="disabled" type="text"
value="{{modal.data.modifiedDate | date:'MM/dd/yy HH:mm'}}" />

To start with it is always better to save the dates on server in UTC. So on the server use the method DateTime.UtcNow.
And while sending the data to client, if you are not custom formatting the date, i believe the date send contains the timezone information as well. AngularJS can handle that correct using date filter. See this fiddle http://jsfiddle.net/jHSLe/1/

Assuming the date you are getting is in UTC, you can use the excellent Moment.js to easily convert it to local time as described here:
http://momentjs.com/docs/#/manipulating/local/

Related

ASP.NET MVC 5 'DateTime' cannot be saved on sql server 'datetime' format on Release (published) mode but works on Debug mode

So I have an ASP.NET MV5 app, I'm using Entity Framework 6 and a SQL Server database. I also use this: datepicker
I have bootstrap-datepicker input with this format: 'dd.mm.yyyy'. With jQuery I get this field's value, which is exactly like this "29.01.2022" and I send it to an ASP.NET MVC action method which expects a DateTime parameter.
On my action that parameter is converted automatically to DateTime format but keeps the correct date.
Datepicker configuration:
$(".input-daterange") {
language: 'ro',
format: 'dd.mm.yyyy',// this gives 29.01.2022
//format: 'dd.MM.yyyy',// this gives 29.Jan.2022
autoclose: true,
calendarWeeks: true,
clearbtn: true,
disableTouchKeyboard: true
}
I'm using Entity Framework 6 for database access, so my code looks something like this:
public Action SaveField(int rowId, DateTime fieldDateValue)
{
var itemToUpdate = _context.TableName.Single(i => i.id = rowId); // this is not null
itemToUpdate.StartDate = fieldDateValue;
try
{
_context.SaveChanges()
}
catch
{ ... }
}
This code works well in debug mode but when I publish the app all gets crazy, I get an error
String was not recognized as a valid DateTime
What I've tried so far (because of datepicker format: dd.mm.yyyy):
itemToUpdate.StartDate = fieldDateValue
itemToUpdate.StartDate = Convert.ToDateTime(fieldDateValue.ToString("yyyy-MM-dd HH:mm:ss")) --> this worked for a few times but the saved date in the database was from 29.01.2022 to 2022-29-01 so something like yyyy-MM-dd, but gives be error too
itemToUpdate.StartDate = DateTime.ParseExact(fieldDateValue.ToString(), "dd.mm.yyyy", CultureInfo.InvariantCulture);
itemToUpdate.StartDate = DateTime.ParseExact(fieldDateValue.ToShortDateString(), "dd.mm.yyyy", CultureInfo.InvariantCulture);
I simply cannot understand what am I doing wrong giving the fact that the published version of the app I'm running on a remote server (which might explain issues) but also on the same machine (IIS wwroot).
Can someone tell how to correctly manage the date format so there will be no more problems and differences between debug and release versions?
So, finally, what actually worked for published version of my app was this:
date format in SQL Server database (datetime not working)
made my filed in ViewModel as 'string' instead of DateTime
DateTime.ParseExact(fieldDateValue, "dd.MM.yyyy", CultureInfo.InvariantCulture)
Build -> Clean project then Publish it (just for safety, when you do a lot of publishing) -> this also solves publish failures with Visual Studio 2015 (first time fail than second get's published)
Also for failed publishing, last solution is to delete obj folder from project
For some reason DateTime.ParseExact(fieldDateValue.ToShortDateString(), "dd.MM.yyyy", CultureInfo.InvariantCulture) didn't work in release mode

Receiving an incorrect time in SQL

I'm interested in getting a full date in SQL this way 2021/02/02 20:12:36
And the date is kept in such a way 2021/02/02 00:00:00
On the server side I get a correct date like this 2021/02/02 20:12:36
On the client side I get this way 2021/02/02 03:00:00
This is the format I get in React
I don't know why:(
Maybe here's the problem
const FormatDate = (date) => {
try {
console.log(date);
return format(date, "yyyy/MM/dd hh:mm:ss");
} catch (e) {
return "";
}
};
I think this is error of browser auto add offset at client
You can try this code to show right time at client
new Date(DATE_REPONSE_FROM_SERVER).getTime() - new Date().getTimezoneOffset() * 60 * 1000
But you need add offset at server if you send this time to server
Other way, I this you convert time to string and response this string
Hope this help for you

Get error when I try to pass date value in URL to web api method

I create this date variable in client side:
this.latestDate = new Date(2001, 1, 1,1,1,1,1);
Here how it looks in client watch:
self.latestDate: Thu Feb 01 2001 01:01:01 GMT+0200 (Jerusalem Standard Time)
here is angularjs service that I use to asyncroniusly call my web api method:
$http.get(serviceUrl + "?date=" + self.latestDate);
And here is the web api method that I call from cilent:
[HttpGet]
public HttpResponseMessage GetByDate(DateTime date){}
But each time I call for web api method above, I get this error on cilent:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'date' of non-nullable type 'System.DateTime' for method 'System.Net.Http.HttpResponseMessage GetByDate(System.DateTime)' in 'SensorObservation.Web.SensorsDataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
Any idea why I get the error above?
First, doing this is a really bad idea:
$http.get(serviceUrl + "?date=" + self.latestDate);
A URL is a structured text format; it has formatting rules that must be followed. When you dump unstructured text into a structured format by using simple string concatenation, you are likely to be breaking some of those rules. I would recommend using the jQuery param function for this.
Second, you are serializing the date to a string using the default format, which is the one you see in the client watch. This may or may not work on the server. A better bet is to serialize using a well known format such as ISO 8601. I would recommend using the JavaScript date toISOString function for this.
Applying these changes, your API call code would look something like this:
var query = jQuery.param({ date: self.latestDate.toISOString() });
$http.get(serviceUrl + "?" + query);
Update
I ran a quick test since I was in my WebAPI code already, and you can create and use an endpoint with a DateTime parameter as long as the URL is formatted correctly.
My test endpoint looks like this:
[HttpGet]
[Route("test/datetest")]
public HttpResponseMessage DateTest(DateTime d)
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent(d.ToString(), Encoding.UTF8, "text/plain");
return response;
}
It echoes the date back as expected.

Grails application showing wrong date

I've developed a grails application with grails-2.4.5, SQL Server 2008 R2 database and facing a strange problem. In one of my domain class there's a field of Date datatype. When i am submitting data from the respective form it saves it correctly to the database but in the show view the date shows two days ago the saved date. As for example I input 08 June 1992, it saves to database as "1992-06-08 00:00:00.0000000", but in the show view it becomes "06/06/1992"
I used the g:formatDate tag in the show page. ( <g:formatDate format="dd/MM/yyyy"
date="${aaaOrganizationInstance?.dateOfEstablish}"/> )
Controllers save action:
#Transactional
def save(AaaOrganization aaaOrganizationInstance) {
if (aaaOrganizationInstance == null) {
notFound()
return
}
if (aaaOrganizationInstance.hasErrors()) {
respond aaaOrganizationInstance.errors, view:'create'
return
}
aaaOrganizationInstance.save flush:true
request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [message(code: 'aaaOrganization.label', default: 'AaaOrganization'), aaaOrganizationInstance.id])
redirect aaaOrganizationInstance
}
'*' { respond aaaOrganizationInstance, [status: CREATED] }
}
}
There's a known issue with the SQL Server JDBC driver that causes your symptom. Here's a related question.
The solution
To fix the issue you can install the updated JDBC driver here.

RPC call to external server

I am a new bie on GWT, I wrote an application on abc.com, I have another application i.e. xyz.com, xyz.com?id=1 provides me a data in json format, I was thinking to find a way that how to get that json file in abc.com via RPC call, because I have seen tutorials in which RPC calls are used to get data from its server. any help will be appreciated.
EDIT
I am trying to implement this in this StockWatcher tutorial
I changed my code slightly change to this
private static final String JSON_URL = "http://localhost/stockPrices.php?q=";
AND
private void refreshWatchList() {
if (stocks.size() == 0) {
return;
}
String url = JSON_URL;
// Append watch list stock symbols to query URL.
Iterator iter = stocks.iterator();
while (iter.hasNext()) {
url += iter.next();
if (iter.hasNext()) {
url += "+";
}
}
url = URL.encode(url);
MyJSONUtility.makeJSONRequest(url, new JSONHandler() {
#Override
public void handleJSON(JavaScriptObject obj) {
if (obj == null) {
displayError("Couldn't retrieve JSON");
return;
}
updateTable(asArrayOfStockData(obj));
}
});
}
before when I was requesting my url via RequestBuilder it was giving me an exception Couldn't retrieve JSON but now JSON is fetched and status code is 200 as I saw that in firebug but it is not updating on table. Kindly help me regarding this.
First, you need to understand the Same Origin Policy which explains how browsers implement a security model where JavaScript code running on a web page may not interact with any resource not originating from the same web site.
While GWT's HTTP client and RPC call can only fetch data from the same site where your application was loaded, you can get data from another server if it returns json in the right format. You must be interacting with a JSON service that can invoke user defined callback functions with the JSON data as argument.
Second, see How to Fetch JSON DATA

Resources