I have created mongodb collection using nodejs as below:
var mongoose = require('mongoose');
var TTTUsersSchema = new mongoose.Schema({
username: String,
password:String,
active: Boolean,
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Users', TTTUsersSchema);
Since creating record the default date is stored as Tue Nov 13 2018
20:53:47 GMT+0000 (GMT Standard Time) so when I fetch this field then it
is displayed in HTML as above. I want to display it in DD/MM/YY HH:MM
format.
Where I need to change? In HTML UI level? or at Mondgodb collection level.
Please help.
Time stamps should always be stored in a consistent way, e.g. like ISODate() in MongoDB, and always be handled in the code in a consistent way, e.g. like Date object in Javascript.
Only when you
present a time stamp to a user as string, or
parse a time string from the user
then you do conversions.
Unfortunately JavaScript Date object is severely limited, so I would suggest to use a package like Moment.js which offers lots of formatting capabilities:
const moment = require('moment');
// date is a Date object you got, e.g. from MongoDB
const time = moment(date);
console.log(time.format("DD/MM/YY HH:mm"));
You need to format your date time at view layer.
one option is to format at your controller if you are using MVC or at the layer that produce view model.
the another option is to format at html using javascript. You may need to use lib like moment.js
Assume current day is Tue Nov 13 2018 20:53:47 GMT+0000
Use .toDateString()
var date = new Date();
console.log(date.toDateString());
It will display:
Tue Nov 13 2018
Related
I'm new in web development.
my problem is:
how to disaply in html a date in simple format dd/mm/yy
instead of Fri Sep 01 2000 00:00:00 GMT+0300 (Israel Daylight Time)
I'm trying to create a crud api using mongoose.
I have a schema model,
one of the fileds is a filed of type date:
joinDate: {type: Date, required: true}
in the controller:
post- program.joinDate= req.body.joinDate;
get-
Program.find((err, docs) => {
res.render("program/list", {
list: docs
});
});
in the view: <td>{{this.joinDate}}</td>
My question: The easy and fast way to convert the long format to short and cleraly format.
I saw some solutions but I think they are too complex and outdated.
If you have any idea for me I would be happy:)
thank's you!
I often use mongoose virtual + moments for this.
eventSchema.virtual('joinDate_formatted').get(function () {
return moment(joinDate).calendar({
sameDay: 'h:mm A',
nextDay: '[Tomorrow] h:mm A',
nextWeek: 'dddd',
lastDay: '[Yesterday] h:mm A',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY h:mm A'
}); //Above shows in calendar format but u can do whatever u want in moment
});
When u do any find on the collection, you will get a joinDate_formatted which u can use on your front end.
I have this API Endpoint setup on Lambda where my applications talk to and get the data it needs.
Problem am running across right now is trying to access an element that is based on the day before today's date.
Language: Python 3.7
Service: AWS Lambda
Provider: WeatherStack
Example: https://weatherstack.com/documentation -> API Features
-> Weather Forecast
In order to access this element from the API provider; I have to basically setup a JSON structure that goes like this:
"forecast": {
"2020-04-04": {
"date": "2020-04-04",
"date_epoch": 1585958400,
"astro": {
"sunrise": "06:42 AM",
"sunset": "07:31 PM",
"moonrise": "03:26 PM",
"moonset": "04:56 AM",
"moon_phase": "Waxing Gibbous",
"moon_illumination": 79
},
"mintemp": 46,
"maxtemp": 54,
"avgtemp": 50,
"totalsnow": 0,
"sunhour": 7.7,
"uv_index": 2
}
}
Now the problem here is the "2020-04-04" date; as I can't access it simply by calling api_endpoint['forecast'][0] as it will throw an error. I checked using Lens however and did find that it does have one element in 'forecast' which is of course the 2020-04-04 that I'm having trouble trying to access.
I don't know if there's a way to dynamically set the element to be called based on yesterday's date since the api provider will change the forecast date element daily.
I've tried api_endpoint['forecast'][datetime.now()] and got an error.
Is there a way to set the [] after ['forecast] dynamically via variable so that i can always call it based on api_endpoint['forecast'][yesterdaysdate]?
Solution:
from datetime import timedelta, datetime
ts = time.gmtime()
todaysdate = (time.strftime("%Y-%m-%d", ts))
yesterday_date = (datetime.datetime.utcnow() - timedelta(1)).strftime('%Y-%m-%d')
data = api_response['forecast'][yesterday_date]
If I understand corectly, you want to call the data inside the api_endpoint['forecast'][yesterday_date].
If so, this can be achieved by this:
from datetime import datetime, timedelta
yesterday_date = (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
# call to api
api_endpoint['forecast'][yesterday_date]
If you want to days ago, change timedelta(2) and so on.
Today variable can be assigned by this:
current_date = datetime.now().strftime('%Y-%m-%d')
api_endpoint['forecast'][current_date]
If none of the above solutions answer to your question, leave a comment.
I have saved the model using
mx.model.save(model = fit_dl, prefix = "model", iteration = 10)
and loaded later
fit <- mx.model.load(prefix = "model", iteration = 10)
Now, using object fit, I want to extract the input features (column names of train data). How to do that
Posting for sake of all open source community
As per my email exchange with maintner of mxnet packge, Qiang Kou replies following
From: Qiang Kou
To: Shiv Onkar Kumar
Sent: Wednesday, 14 June 2017 10:33 PM
Subject: Re: Extract Input parameters from “mxnet” model
Hi, Shiv,
I don't this is possible since we never store this information in the model.
Best,
Qiang Kou
I am facing an issue in test case when i am trying to do deepEqual where i am trying to compare the exact structure of result data with sample data.
the above is my sample json data which i created with the result of the actual data.
Code:
it('comparing structures',()=>{
var result = instance.parseResponse(input,esResponse);
console.log(result);
assert.deepEqual( result, expectedJSON);
});
Here in console i am getting the result .
Taking the result i am creating the sample data .
Code :
var expectedJSON={
"response":{
"aggregate":{
"average":43.833333333333336,
"count":6,
"max":90,
"min":10,
"total":263
},
"endDate":"Tue Jul 05 2016 05:30:00 GMT+0530 (India Standard Time)",
"groupBy":"datetime",
"metricType":"distance_metric",
"quarters":[{
"aggregate":{
"average":0,
"count":undefined,
"max":0,
"min":0,
"total":0
},
"quarter":4,
"startDate":"Invalid Date"
}],
"startDate":"Tue Jan 12 2016 05:30:00 GMT+0530 (India Standard Time)",
"type":"person"
}
};
I am doing this because i need to create the exact Json structure and let anything may be the result the structure should match .
but i am getting the fail test case
deepEqual have a lot of issues and is old now. Lot of new ECMA features aren't supported either. I found this one very interesting: https://github.com/zubuzon/kewlr
When you use deepEqual it checks not only the structure of the object but also the type of object. In this case it is given by __proto__
I have to define a date in my Student Object,like that:
var Students = new List<Student>
{
new Student{ FirstName="Student ",dateBirth=DateTime.Today }
};
Students.ForEach(s =>
{
s.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
context.Students.Add(s);
context.SaveChanges();
});
but I get this format when I run my project:
[{ FirstName: "Student ", dateBirth: "/Date(1457132400000)/" }]
the problem is that the date format is added exactly to the DataBase Student Table (like yyyy-MM-dd hh:mm:ss). I work with xampp MySQL
any idea please how can I solve this problem,and display the date correctly?
Try formatting the date time like this:
new Student{FirstName="Student ",dateBirth=DateTime.ToString("MMMM dd, yyyy")}
You can read up on the details here.
Custom Date and Time Strings