I'm trying to validate some input with hapijs/joi and joi-date-extensions
. I write this code example1.js:
const BaseJoi = require('joi');
const Extension = require('joi-date-extensions');
const Joi = BaseJoi.extend(Extension);
const schema = Joi.object().keys({
start_date: Joi.date().format('YYYY-MM-DD').raw(),
end_date: Joi.date().min(Joi.ref('start_date')).format('YYYY-MM-DD').raw(),
});
const obj = {
start_date: '2018-07-01',
end_date: '2018-06-30',
}
console.log(schema.validate(obj));
the code returns this error:
child "end_date" fails because ["end_date" must be larger than or equal to "Sun Jul 01 2018 01:00:00 GMT+0100 (CET)"]
However I want to get the original input in the error, somthing like that:
child "end_date" fails because ["end_date" must be larger than or equal to "2018-07-01"]
When I tried this instruction in the example2.js:
start_date = Joi.date().format('YYYY-MM-DD');
console.log(start_date.validate('2018-07-31'));
The result was:
Tue Jul 31 2018 00:00:00 GMT+0100 (CET)
when I use the raw() in the example3.js:
start_date = Joi.date().format('YYYY-MM-DD').raw();
console.log(start_date.validate('2018-07-31'));
it returns:
"2018-07-31"
In the example1.js I want to get the original date entred by my code. How can I fix that?
.raw controls how data is transmitted to Joi.validate's callback, i.e. what your data looks like after the validation process. It does not control what happens on errors.
To do that, you may want to use .error. I never used it but I guess it'd be something like this:
Joi.date().min(Joi.ref('start_date')).format('YYYY-MM-DD').raw().error(function (errors) {
var out = [];
errors.forEach(function (e) {
out.push(e.message.replace(/".*?"/g, function(match) {
var dateMatch = Date.parse(match);
if (isNaN(dateMatch)) {
return match;
} else {
// return formatted date from `dateMatch` here, too lazy to write it in p[l]ain JS...
}
}));
});
return out;
})
Related
I've checked all the other forums asked on the forums here tried the clone method doesn't seem to work either. What I'm trying to do is make a key claim system and it'll get the current date and add whatever number the key has assigned to it for example key is assigned 10 days it'll add 10 days to the date. Yet it doesn't add time.
This is what it returns to console when trying to add 10 days
Thu Nov 10 2022 19:42:29 GMT-0500
Here's my code
let userDB = await userSchema.find({ UserID: id });
let keysDB = await keysSchema.find({ Key: key });
var todayTime = moment(new Date());
let todayCurTime = todayTime.clone();
userDB = new userSchema({
Name: name,
Discrim: discrim,
UserID: id,
Time: todayCurTime.add(keysDB.Time, 'days')
})
console.log(`Updated time ${todayCurTime.add(keysDB.Time, 'days')}`)
await userDB.save().catch(err => console.log(err));
Moment.add() mutates the original moment rather than returning an updated moment object (source from docs). It appears that it does return a moment, but specifically the value that the moment had before it was updated. This is a rather odd way to implement things, to say the least, so it's not surprising that it tripped you up.
You need to do your time manipulation before you read from the value. The following should work:
let userDB = await userSchema.find({ UserID: id });
let keysDB = await keysSchema.find({ Key: key });
// You don't need to pass a Date() object if you just want the current date & time
const todayTime = moment();
const todayCurTime = todayTime.clone();
todayCurTime.add(keysDB.Time, 'days')
userDB = new userSchema({
Name: name,
Discrim: discrim,
UserID: id,
Time: todayCurTime
})
console.log(`Updated time ${todayCurTime}`)
await userDB.save().catch(err => console.log(err));
I am trying to get the post created date in this format Jun 20, 2020 when i do this {{ post.created_at }} it shows like this Fri Jul 03 2020 23:43:41 GMT+0100 (West Africa Standard Time) i want to change it to show Jun 20, 2020.
And also i have a posts table in my database and i have user_id column which contains the id of the user that make the post, how can i get the username, i tried doing this {{ post.users.username }} and it shows undefined
Model
'use strict'
const Model = use('Model')
const moment = require('moment');
const date = new Date();
class Post extends Model {
static formatDates (field, value) {
if (field === 'created_at') {
return value.format('MMM D, YYYY')
}
return super.formatDates(field, value)
}
}
My View
<h1>{{ post.created_at }}</h1>
You will have to format your date.
Make changes in your code accordingly.
const moment = require('moment');
const date = new Date();
console.log(moment(date).format("MMM D, YYYY")
As I can see in documentation you have to format your date inside your model
Example
class User extends Model {
static formatDates (field, value) {
if (field === 'created_at') {
return value.format('MMM D, YYYY')
}
return super.formatDates(field, value)
}
}
static castDates(field, value) {
if (field === 'created_at') {
return value.format('MMM D, YYYY')
}
}
I think castDate should work.
Adonis uses moment internally
You can achieve the format without using any package in that way.
var date = new Date('Fri Jul 03 2020 23:43:41 GMT+0100 (West Africa Standard Time)').toDateString();
console.log([date.slice(4, 7), ',', date.slice(7)].join(''))
Mongoose is saving date-time as ISODate("2017-04-25T09:40:48.193Z")in UTC format. How can i change its time zone to my local server timezone. So i need not to change the time every time i retrieve it from db. Here is my model schema:
var MyModelSchema = new mongoose.Schema(
{
id: Number,
description: String,
created: {type: Date},
modified: {type: Date, default: Date.now},
},
{
collection: 'my'
}
);
PS: I am aware that it is preferred to save time in UTC format but here my requirement is to save it in specified time-zone.
you can save users timezone and while updating add the time zone value to this new object. Better to use moment.js to convert this.
moment
Even thought it is not a good practice to store time in local format but this might help -
date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
changes will be done where you are saving the Object -
var date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
var localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
var newModel = new ModelSchema()
newModel.description = 'Something';
newModel.created = locaDate;
newModel.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
I think I have a solution. Try this one for Asia/Calcutta this can be stored as Date type in Mongoose
function getCurrentIndianDateTime(){
var moment = require('moment-timezone');
var time = moment.tz('Asia/Calcutta').format("YYYY-MM-DDTHH:MM:ss");
return new Date(time);
}
I'm writing a React Application that uses MongoDB as its database. There seems to be some strange behaviour when saving and retrieving dates from the database, specifically when updating the date in a particular document.
When I create a new document, everything is fine. However, if I try to edit the date on that document using an ajax call, the date stored in MongoDB is one day earlier than the one I selected and what is displayed in the browser. Code below to explain a little more.
The date is selected using an HTML5 <input type='date' /> element. Here's some of the code. I've included console logs at various points to show the output. Let's assume I'm selecting '30 October 2016' as the date. The date and the year get split up for display purposes elsewhere, but then joined together in the form of a JS Date object before sending to the server (see code below)
React component method:
saveChanges(e, cancel){
e.preventDefault();
const cancelled = cancel ? true : false
console.log(this.state.date); // 30 Oct
console.log(this.state.year); // 2016
const saveData = {
id: this.props.data.id,
venue: this.state.venue,
unitNumber: this.state.unitNumber,
unitName: this.state.unitName,
date: this.state.date,
year: this.state.year,
day: this.state.day,
tutorID: this.state.tutorID,
cancelled: cancelled
}
editWorkshop(saveData, (data) => {
this.props.getWorkshopDetails();
this.props.workshopDetailsSaved(data);
});
}
The above method sends the data to editWorkshop.js, an external ajax call, using axios:
import axios from 'axios';
export default function editWorkshop(input, callback){
const date = new Date(input.date + ' ' + input.year) // Rejoin date and year and convert to Date object
console.log(date); // Sun Oct 30 2016 00:00:00 GMT+0100 (BST)
const data = {
id: input.id,
venue: input.venue,
unitNumber: input.unitNumber,
unitName: input.unitName,
date: date,
day: input.day,
tutorID: input.tutorID,
cancelled: input.cancelled
}
axios.post('/editWorkshop', data).then(function(res){
callback(res.data);
})
}
And finally the express route which handles the ajax call
const express = require('express');
const Workshop = require('../data/models/Workshop');
module.exports = function(req, res){
const data = req.body
console.log(data.date); // 2016-10-29T23:00:00.000Z - here is where it seems to go wrong - notice that the date has changed to 2016-10-29 instead of 10-30. This now gets written to the database
Workshop.update({ _id: data.id }, {
$set: {
unitNumber: data.unitNumber,
date: data.date,
venue: data.venue,
tutor: data.tutorID,
session: data.day,
cancelled: data.cancelled
}
}, function(err){
if (err) {
res.send(err);
return
}
var message = 'Workshop updated'
res.send({
success: true,
message: message
});
})
}
What's really strange is that when I retrieve the data from the database elsewhere in the application, it shows the correct date in the browser - 30 Oct 2016.
Arguably this isn't a problem as the correct date is being displayed, but I'm not comfortable with this as these dates are a fundamental part of the app and I'm concerned that there could be scope for a bug in the future.
Can anyone shed any light on this?
2016-10-29T23:00:00.000Z is same as Sun Oct 30 2016 00:00:00 GMT+0100 (BST).
2016-10-29T23:00:00.000Z is in UTC(GMT) timezone. If you convert that to BST you will get the same value.
MongoDB saves the date values as UTC milliseconds since the Epoch.
From the docs:
MongoDB stores times in UTC by default, and will convert any local
time representations into this form. Applications that must operate or
report on some unmodified local time value may store the time zone
alongside the UTC timestamp, and compute the original local time in
their application logic.
I am trying to format a date type property on a model before displaying it. This is the code that I am using:
// MODEL
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: String,
content: String,
author: { type: String, default: 'Vlad'},
postDate: { type: Date, default: Date.now }
});
ArticleSchema.methods.formatTitle = function() {
var link = this.title.replace(/\s/g, '-');
return '/article/' + link;
};
ArticleSchema.methods.snapshot = function() {
var snapshot = this.content.substring(0, 500);
return snapshot;
};
ArticleSchema.methods.dateString = function() {
var date = new Date(this.postDate);
return date.toDateString();
};
module.exports = mongoose.model('Article', ArticleSchema);
And on the client side I try to display the formatted date using:
{{ article.dateString }}
Still, whenever I load a view that contains this element, I get a 500 error:
Cannot call method 'toDateString' of undefined
EDIT1: I have no issue embedding {{ article.snapshot }} in my Views, but when it comes to the Date object, I get an error
EDIT2: When logging the dateString method using console.log(article.dateString()) I get the following:
Wed Sep 18 2013
EDIT3: This is when I get when using the code provided by dankohn. Is it just me, or is it simply running the method two times in a row?
this.postdate: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
parsed: 1379536022000
date: Wed Sep 18 2013 23:27:02 GMT+0300 (EEST)
toString: Wed Sep 18 2013
Wed Sep 18 2013
this.postdate: undefined
parsed: NaN
date: Invalid Date
toString: Invalid Date
I've rewritten this to make perfectly clear where your date stuff is failing:
ArticleSchema.methods.dateString =
console.log('this.PostDate: ' + this.postDate)
var parsed = Date.parse(this.postDate)
console.log('parsed: ' + parsed)
var date = new Date(parsed);
console.log('date: ' + date)
var toString = date.toDateString();
comsole.log('toString: ' + toString)
return toString;
};
Separately, if this doesn't work for you, I recommend the library moment, which is much easier to work with than native Javascript dates.