Time string to date object conversion js angularJS - javascript

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.

Related

React code to display date in Formatted Way and limit future dates

In REact I am having a state variable like this
const [ dob, setDob ] = useState();
and in the jsx I am having like this
<input type="date" max="new Date()" value = {dob} onChange={(e)=>setDov(e.target.value)}/>
I am facing two issues
I am unable to limit future dates i.e all the dates after today cant be selected but when I am giving max attribute as I am unable to limit the future date
new Date() or new Date().getTime()
I need to show the date after selection in this format DD/MM/YYYY I am unable to display the converted date.For it I tried modyifying the onChange() as onChange()=>setDob(new Date(e.target.value.tolocaleTimestring()))
But still its not working. I am getting error toLocaleString() is not a function
Notes:- I am using React and purely functional components
If you look at the MDN docs for date type and constraining the inputs, you can use min and max attributes on input. So what you did is right except passing a string to max. It needs to be a string (parsable to date) or date object I think.
e.g.
<input type="date" max={new Date()} value = {dob} onChange={(e)=>setDov(e.target.value)}/>
Refer - https://developer.mozilla.org/en-US/docs/Learn/Forms/HTML5_input_types#constraining_datetime_values for more details.
You have multiple error/problem in the code:
1- You can't add JS code in html variable, the HTML max property accept texts. and another issue you had there (event if max accepts JS expression) is that new Date () dosen't match the format it accepts, you have to convert it ISO standard i.e. new Date().toISOString().
2- I am not sure whats the issue you are facing here, belwo I added a snippest that worked for me, that resolved both (1 and 2).
const [ dob, setDob ] = useState();
const today = new Date().toISOString();
return (
<div >
<input type="date" max={today} value = {dob} onChange={(e)=>setDob(e.target.value)}/>
</div>
);

how to send datetime dataframe to django template and plot it in js using plotly

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.

Laravel Timestamp Format / JavaScript Date

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.

How can I use angular-moment to set the format?

I have a date, that look like this(from json):
detailAssets.CONTRACT_END_DATE = '201811';
and I am using angular-moment to format to date, but results are not correct
<tr ng-repeat="assetsdetail in detailAssets | filter:profileId">
<td>{{assetsdetail.CONTRACT_END_DATE | amDateFormat : 'YYYY-MM'}}</td> // shows 1970-01
</tr>
how can I set the format using angular-moment, like this`? :
moment(detailAssets.CONTRACT_END_DATE, 'YYYYMM')
because the above method worked in console and showed the right results : 2018-11
Is detailAssets an array or object?
If it's an object, you should not use ng-repeat on an object.

custom filter expression for a specific part of a string in angular.js

I want to make a custom filter that only displays the 12th character - 16th character of the string
I made this filters.js file :
angular.module('customFilters', []).filter('specificDate', function() {
return function(input) {
};
});
The things i want to put the expression on are all the options from this select item :
<select ng-model="selectedSong" ng-options="song as song.played_at for song in songs.tracks"></select>
In angular you can format date types. In you case you can use like this:
<p>{{song.playedAt | date:'hh:mm'}}<p/>
AngularJS Date Filter

Categories