I've looked around, but haven't been able to find a clear way of returning Laravel timestamps / datetimes in a particular format. It doesn't really matter to me how it's saved in the database, but when I'm pulling the data, I'd like to format it so that it can be parsed by JavaScript. Does someone know of a good way that doesn't involve having to create multiple accessors?
Edit: To add more detail, I'm actually using AngularJS and would like the date returned in a format so that it can be understood by Angular and its date filter. With the current format, the date filter doesn't work because it can't parse the date, from what I can tell.
To define an accessor, create a getFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access.
So, you should define an accessor for the test_date (or anything else) attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of test_date.
(In the example I'll define it in the User model)
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
protected $table = 'users';
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then you'll see the following format by default:
$user = User::find(1);
$user->test_date; //2015.11.12. 8:50:20
If you'd like to write simplier code, you should use Traits.
Let's define the DateTrait in App\DateTrait.php file:
<?php
trait DateTrait {
public function getTestDateAttribute($date) {
//What format do you store in db?
$storedformat = createFromFormat('Y-m-d H:i:s', $date);
//What format would you like to show?
$customformat = $storedformat->format('Y.m.d. H:i:s');
return $customformat;
}
}
Then use it every model where you'd like to format the test_date column.
<?php
namespace App;
use Carbon\Carbon;
class User extends Model {
use App\DateTrait;
...
}
In your view just do something like this:
$variable->created_at->format('m-d-y')
This page here may be useful for getting familiar with Carbon dates and how you can use and format them.
Regarding the parsing of them to a format Javascript can interpret, perhaps you could do something like this - assuming it is coming from an eloquent object you have pulled in to a view or something like that:
{{ (new Carbon\Carbon($dataPassedIn->created_at))->format('F d, Y H:ia') }}
Which would return a date like this September 02, 2015 09:43am, although I'm not sure of the exact format you would need for parsing in to javascript.
Related
So I am returning a date value from my backend API.
This is my model:
public class Sales {
....
public DateTime DateCreated {get;set;}
}
I return it from my Controller:
[System.Web.Http.HttpGet]
public async Task<Sales> GetSales() {
.....
Sales s = await GetSalesForTheUser();
return s;
}
The DateTime value returned by the Controller is missing the Z at the end of it.
The returned value is: 2021-07-27T05:23:41.937 this is wrong because when I parsed it in the Javascript, it is treated as local date time. When I added Z at the end of it (2021-07-27T05:23:41.937Z) then this is right. The date parsing from the Javascript is giving me the correct value.
How can I fix the correct parsing value from my backend (C#)?
It sounds like the problem is within your DateTime object's Kind, and not the serialization.
If the DateTime.Kind is either Local or Unspecified, serializing this in ISO8601 will omit the timezone information (in your case Z, which indicates UTC).
To fix this, first start by trying to specify the kind of your DateTime before returning the data. See here how: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.specifykind?view=net-5.0.
If that works, inspect your service, and see if you are correctly interpreting the data returned to populate the property Sales.DateCreated, and ensure this is in UTC.
I recommend using NewtonJson:
Add the package to your project
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="..." />
and you can achieve it by adding some configurations to your Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
// Configure controllers.
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffZ"
});
});
...
}
If you want to change it on the backend, then create another property in
your Sales class like "DataCreatedFormated" of type string and public string DateCreatedFormated => DateCreated.ToString(format); where "format" is one from this article.
I suggest 'u' format.
I have a data-frame and I want to send it in my Django template.
dummy code in views.py:
def graphs(request):
df_new = pd.read_excel("/home/cms/cms/static/Sensorik.xlsx")
times = df_new.loc[:, df_new.columns[0]].to_json(orient='records')
# columns[0] contains datetime values
data_color = df_georgian.loc[:, df_georgian.columns[2]]
color = data_color.to_json(orient='records')
context = {
'times': times,
'data_color': color,
...
}
return render(request, 'graphs/graphs.html', context)
In my template, I get these data like the following:
<script>
var times = {{ times|safe }};
console.log('index: ', typeof(index));
var color = {{ data_color|safe }};
</script>
the color variable is totally ok but the times variable when get to JSON format turns from 2018-05-29 08:09:00 format to something like it:
element: 1528108200000
I want to be able to plot the color based on times to get a line graph with plotly. i.e. I want to show times as x-ticks of my plot.
any suggeston on
1- how to send datetime dataframe to django template?
or
2- how to convert element: 1528108200000 into a datetime in js to plot it as x-ticks?
Whenever you see something that should be a date or time expressed in a large number like the 1528108200000 format, that means it is or is similar to a UNIX timestamp—the number of seconds past January 1, 1970. In this case, the length of the timestamp indicates that it's milliseconds, not seconds, so it's not exactly a UNIX timestamp but is very close.
Milliseconds since January 1, 1970 is the way that JS internally stores Date objects, which is interesting because it means some sort of conversion is probably happening on the JS side, not the python side (where you'd usually get ISO format or UNIX Timestamps).
In any case, it's pretty easy to solve on the JS side because you can simply parse the number:
dateObject = new Date(1528108200000);
If you do that parsing and pass the data to Plotly as Date objects, Plotly should be able to recognize your dates.
A simple way to do that would be:
const times = [1528108200000, 1528108200000, 1528108200000]
const parsed = times.map(time => new Date(time))
assuming your times variable is just an array of these integers.
I am getting following string from REST api,
20160220
I want to make it 20/02/2016
I am using angularJS. So I will require a filter.
I have tried following
app.filter('myDateFilter', function() {
return function(input) {
var st = input;
var pattern = /(\d{4})(\d{2})(\d{2})/;
var date = new Date(st.replace(pattern, '$1-$2-$3'));
return date;
}
});
And in html I have used
<td>
{{t["due-date"] | myDateFilter}}
</td>
This returns 2016-02-20T00:00:00.000Z
Regular expression issue? Can you kindly give me proper code which should have been used instead to generate 20/02/2016.
Naively converting a Date into a string results in the output you are seeing:
console.log(new Date()) // "2016-09-02T15:19:07.921Z"
Instead, make sure you format the date into a string manually before returning it. E.g. toLocaleDateString() converts the Date into a string, taking into account the browser's locale:
console.log(new Date().toLocaleDateString()) // "09/02/2016"
What you are doing is converting a String to a Date() object, which seems right to me. If you try to show your Date() object in your view, what you get is the default date format.
In order to customize the format in which your Date() object is showing, you need to chain another filter to your custom filter. In this case you need to use date filter: https://docs.angularjs.org/api/ng/filter/date
You would only need to add it to your template, like this:
<td>
{{t["due-date"] | myDateFilter | date : 'dd/MM/yyyy'}}
</td>
This way date filter will take as input the Date() object returned by your custom myDateFilter filter and produce a String representing that object as output.
This is a nice example of how angular filters and filter chaining are supposed to be used.
I have a table called flagged_posts with the following rows:
id
thought_id (id of the post being flagged)
user_id (id of the user who is flagging the post)
I am trying to implement a graph which (for now) will show how many flagged posts have occured ed for the current date (x-axis will show days, i.e. monday, tuesday etc, y-xis will show number of incidents).
I have seen charts.js but, I am unsure whether these charts can be used based on database data. I.e. if monday has 10 flagged incidents, $mon_flagged = 10, then use the variable to display data in the graph? or in another way which automatically gets data from db?
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/You first need to build your data into an array that will be in a useful format for the chart library.
After you have selected the relevant data, format it into an array something like this:
function formatDataForChartsJs($result){
while ( $row = mysql_fetch_assoc( $result ) ) {
if($row['post_is_flagged']) {
$data[$row['date_created']] += 1;
}
}
return $data
}
Then you should end up with an array suitable for use with your javascript charting library. Something like this:
$data = [
2016-03-7 => 10
2016-03-08 => 15
...
]
You then need to understand how you will pass the data to front end so that you can use your data with a javascript chart library.
The normal way to do this it to take your php data variable and encode it as a json string.
$data = fetchData();
$formattedData = formatDataForChartsJs();
$dataAsJsonString = json_encode($formattedData);
Then in your view:
<script type=text/javascript>
var graphData = <?php echo $dataAsJsonString ?>
//use your graph data variable with chart.js or other javascript graph library
</script>
There is a good tutorial here, but I would advise using json_encode rather than their approach to printing a JSON string.
https://www.amcharts.com/tutorials/using-php-to-hook-up-charts-to-mysql-data-base/
I am returning JSON data from a remote server which holds some information. (The product name and the date).
I want to modify the date output in my handlebars template. Here is a JSBin with my code.
Should I use a property in order to change the format of the date? Or there is a better way to do that? If yes, what should I do?
Thank you in advance.
Ember Helper:
The better way to do it is to use an Handlebars Helper to convert your date into a useable format. The reason a helper is better than a computed property, is it can be reused throughout your code anywhere you need to format a date in the template.
I have updated the JSBin to use this helper.
Helper:
Ember.Handlebars.helper('dateformat', function(value) {
// Use moment, or alternatively use JavaScript date and return your own custom string
return moment(value).format("DD/MM/YY"); // Change to suitable format. See http://momentjs.com/docs/
});
Usage:
{{dateformat item.date}}
Note:
This example uses the MomentJS library to convert the date into format DD/MM/YY but obviously you can change this.
It is possible to do the conversion without using this external library, using the standard JavaScript date object. The helper just needs to return the formatted string.
Computed Property:
To do it as a computed property requires a little more effort. You can see a working demo of this here. The demo uses a modified version of your localeDate function.
Ember Object with Computed Date Property:
So create a HistoryItem object that has the computed property.
App.HistoryItem = Ember.Object.extend({
localeDate: function() {
var dt = new Date(this.get('date'));
return dt.toLocaleDateString() + " " + dt.toLocaleTimeString();
}.property('date')
});
Update Model:
The model is a plain object, you need to create an instance of the HistoryItem for each item in your history.
App.IndexRoute = Ember.Route.extend({
model: function() {
// Get the history
var history = App.JsonRequestFromRemoteServer.history;
var result = [];
// Create item as history item
history.forEach(function(item){
result.push(App.HistoryItem.create(item));
});
// Return the result as the model
return { history: result };
}
});
Hope this helps.
To address why your JSBin here didn't work:
You were trying to use property("history.#each.date"), to create a computed property on each item in the collection.
Unfortunately what this does is provide what's called an Aggregated Property. You can read more about aggregated properties here, but essentially that would give you one property on your history object based on all the dates in the collection. Not a single property on each item as desired.
I do think this is an area of Ember that should be better covered in the documentation, you're not the first person to think you can add computed properties to collections that way.