var Timeframe = React.createClass({
getInitialState: function() {
return {
tfs: getParameterByName('tfs'),
tfe: getParameterByName('tfe')
}
},
formatTime: function(time) {
var full = new Date(time);
console.log(time);
console.log(full);
return (full).toString('dddd, MMMM ,yyyy');
},
render: function () {
return (
<div>Timeframe: {this.formatTime(this.state.tfs)} - {this.formatTime(this.state.tfs)}</div>
);
}
});
I have an outside js function called getParameterByName which, in these cases, is going to return a time in unix time. As far as I know, Date() works very well with these numbers, and in my experience outside of React, I've never had any trouble with this. When I try using Date within my react function, it's returning invalid date. Does anybody know why this might be happening?
Try this: full.toString('dddd, MMMM ,yyyy');
Instead of: (full).toString('dddd, MMMM ,yyyy');
If you need to work with date, a good choice is to use Moment library.
Related
First I'll say that I've tried the solution in How do I use .toLocaleTimeString() without displaying seconds?
and it didn't work for me.
I am trying to create a timer component with the h:m:s format but I always see the full current date. Does anyone have a solution?
Here is my code:
import React , { Component } from 'react';
class Timer extends Component {
constructor (props) {
super(props);
this.state = {
count : 0
}
}
render () {
{
var hour = Math.floor(this.state.count/3600),
minutes = Math.floor((this.state.count - hour*3600)/60),
seconds = (this.state.count - hour*3600 -minutes*60 ),
date = new Date();
date.setHours(hour, minutes, seconds);
}
return(
<div>
{date.toString( {hour: '2-digit', minute:'2-digit'})}
</div>
);
}
}
export default Timer;
What I'm getting from this component looks like this:
Is it related to how react-js is working or am I writing the javascript code wrong?
you can do it like this:
//your date
let temp = new Date();
let HMS = `${temp.getHours()}:${temp.getMinutes()}:${temp.getSeconds()}`
and now you have your hours:minutes:seconds
I'm developing a datepicker using pure javascript. The datepicker works fine, but i have a problem that i dont know how to solve:
I have this line:
var my_cal = new Calendar("cal","2020-01-1","2022-01-01","2021-06-14");
that declare the Calendar object. Among the variables of the object, there are 2 variables whose value is the picked dates:
this.FromDate=null;
this.ToDate=null;
Also,there is a function that executes when the user clicks on one of the dates in the calendar, and the function according to the conditions, defines the two variables I mentioned above.
this.date_pick=function()
{
if(my_cal.FromDate==null){
my_cal.FromDate=new Date(this.getAttribute("data-date"));
console.log("From Date "+my_cal.FromDate);
}
else {
if(my_cal.ToDate==null){
let todate=new Date(this.getAttribute("data-date"));
if(todate>my_cal.FromDate){
my_cal.ToDate=new Date(this.getAttribute("data-date"));
console.log("To Date "+my_cal.ToDate);
}
}
else {
my_cal.FromDate=new Date(this.getAttribute("data-date"));
console.log("From Date "+my_cal.FromDate);
my_cal.ToDate=null;
}
}
my_cal.create();
};
The problem is that I need to call directly to the my_cal variable to make the function work, and I want it to work for each calendar individually created by the page.
I tried to change the my_cal. to this., like that:
this.date_pick=function()
{
if(this.FromDate==null){
this.FromDate=new Date(this.getAttribute("data-date"));
console.log("From Date "+this.FromDate);
}
else {
if(this.ToDate==null){
let todate=new Date(this.getAttribute("data-date"));
if(todate>this.FromDate){
this.ToDate=new Date(this.getAttribute("data-date"));
console.log("To Date "+this.ToDate);
}
}
else {
this.FromDate=new Date(this.getAttribute("data-date"));
console.log("From Date "+this.FromDate);
this.ToDate=null;
}
}
this.create();
};
but I get this error:
Uncaught TypeError: this.create is not a function
at HTMLTableCellElement.Calendar.date_pick
and I really dont know what to do.
codepen for the whole project: https://codepen.io/DavidiAllove/pen/YzZMgGg
Thanks for the helpers !! :)
EDIT:
I changed the self to this, I get the same error.
I'm building a JavaScript class and I would like to return a result at the end of a method chain without calling a specific method.
Example 1: myDate('01/01/2000').add(1, 'day') should return 01/02/2000.
Example 2: myDate('01/01/2000').add(1, 'day').format('MMMM D YYYY') should return January 2 2000.
I know that this is possible using a JS class because saw it working in DayJs, I just don't understand how: https://github.com/iamkun/dayjs/blob/dev/src/index.js#L77
For now, what I have looks like this:
class MyDate {
constructor(date) {
this.date = date;
}
add(count, unit) {
this.date = // function
return this; // to enable method chaining
}
format() {
this.date = // function
return this.date; // to return the desired result
}
get() {
return this.date;
}
}
// wrapper function to instantiate class on function call
const myDate = date => new MyDate(date);
With this setup, I get the following behavior:
Example 3: myDate('01/01/2000').add(1, 'day') returns { date: 01/02/2000} instead of 01/02/2000.
Example 4: myDate('01/01/2000').add(1, 'day').format('MMMM D YYYY') returns January 2 2000 as expected.
Example 5: myDate('01/01/2000').add(1, 'day').get() returns 01/02/2000 but there is that nagging get() that I would like to eliminate...
I googled the issue, "js detect end of method chain" and such, but I couldn't find any results that would explain how this works.
Thanks for your help!
Logically speaking add method on a class should return the object instance instead of a particular member variable.
What you have as of now is perfect and that's how any user would expect it to work.
Imagine a case where you had to add another member variable, say time to your class and you want to chain something like object.add(1, 'day').add(5, 'hour'). You can achieve this only if your add function returns an instance of your class.
It is also perfectly fine to have to attach a get() method at the end. Consider the famous moment.js package. Even they have a format() method to get the actual date object.
Hope this clarifies your confusion.
Looking back at it, what I wanted to do was a class that had the following features:
import myDate from "./myDate.js"
import { isMyDate } from "./myDate.js"
No need to use the new keyword to instantiate
Can pass an unlimited number of arguments
With function chaining
console.log(myDate(params)) outputs a custom string MyDate<date_in_ms)>
${myDate(params)} outputs a custom string date_in_ms
Here is a possible implementation of it:
// Custom console.log
// Deno: https://doc.deno.land/builtin/stable#Deno.inspect
const inspect = Symbol.for("Deno.customInspect")
// Node: https://nodejs.org/api/util.html#util_util_inspect_custom
// const inspect = Symbol.for('nodejs.util.inspect.custom');
class MyDate {
constructor(date = new Date(), options) {
// Set the class's properties
this._date = date;
this._options = options;
// Run initialization tasks
this.initialize();
}
initialize() {
// if Date, convert time to milliseconds
if (this._date instanceof Date) {
this._date = this._date.getTime();
}
}
// Output the result
format() {
return this._date;
}
// Chainable function
add(amount) {
this._date += amount;
return this;
}
// Output all the parameters past after the first one
options() {
return this._options;
}
// Custom console.log
[inspect]() {
return `MyDate<${this._date}>`;
}
// Custom String output
toString() {
return `${this._date}`;
}
}
// Automatically instantiate class
const myDate = (date, ...options) => {
return new MyDate(date, options);
}
// Stand-alone function
const isMyDate = date => date instanceof MyDate;
// Access the stand-alone funtion from the MyDate instance
myDate.isMyDate = date => isMyDate(date);
export default myDate;
export { isMyDate };
Link to Dev.to article: https://dev.to/rildev/modern-es6-class-48pb
Link to live proof-of-concept: https://replit.com/#RilDev/ModernES6Class
This is my mixin in Vue.js:
var myMixin = {
data () {
clockInt: '',
clock: '',
currentTime: new Date()
},
mounted () {
this.intervalSetup();
},
methods: {
intervalSetup () {
var _this = this;
// init
this.getTime();
// start interval every 60s
this.clockInt = setInterval(
_this.getTime(), 60000
);
},
getTime () {
var now = this.currentTime,
h = now.getHours(),
m = now.getMinutes();
this.clock = h + ':' + m;
}
}
};
This should display a simple digital watch which sets the time every 60s.
Then, I register this mixin to Vue, require my component and start a new instance of Vue:
Vue.component('comp', require('./components/MyComponent.vue'));
Vue.mixin(myMixin);
const app = new Vue({
el: '#app'
});
My component looks like this:
<template>
<div>{{ clock }}</div>
</template>
<script>
export default {
data () {
return {
someData: []
}
},
mounted () {
// call methods
},
methods: {
// some methods
}
};
</script>
The first init of the mixin method works fine and as I can see in the Vue dev-tool, all data is present too. But it does not refresh the data in the interval I set up.
Hopefully someone had similar issues and can help me with this.
Well guys. Both solution work exactly as expected - as a single component and as a mixin. Good to know.
The issue was currentTime: new Date(). The date time was declared in data object only once. So the interval always took this timestamp.
I just removed this and changed var now = new Date(); in my mixin's method.
Thank you guys!
I have piece of code in js like this:
var obj = (function(){
var stateObj = {key:"privateValue"};
return {
getState: function() {
return stateObj.key;
},
publicFn : function(){
//do some operation with stateObj
if(getState() == "test") {
//. . . .
}
}
}
}());
and I tested the code like this:
//test case
sandbox.stub(obj.getState,"test")
assertItShouldGoInsideIfLoop(obj.publicFn())
However on the code review, my team lead said, this is wrong and he asked me to use Dependency injection for these cases.
I really don't know why the above approach is wrong or even why one should use DI.
If I'm interpreting this correctly, the issue here is that your test for the value of calling publicFn depends on the value of stateObj. The entire idea behind dependency injection is that you provide some means to supply these values in your tests in order to decouple the data from the behavior of the function under test.
var obj = (function(){
return {
setStateObj: function(stateObj) {
this.stateObj = stateObj;
},
getState: function() {
return this.stateObj.key;
},
publicFn : function(){
//do some operation with stateObj
if(getState() == "test") {
//. . . .
}
}
}
}());
Now we can use setStateObj to set the state as needed in our tests instead of stubbing the value, which can be dangerous:
obj.setStateObj({ key: 'test' })
assertItExecutesIfStatement(obj.publicFn())
obj.setStateObj({ key: 'blah' })
assertItDoesntExecuteIfStatement(obj.publicFn())
So why is this preferred to stubbing getState? Say we comment the contents of getState:
getState: function() {
// return this.stateObj.key;
}, // returns nothing, but you're stubbing it to return "test" anyway!
Clearly, this function will not work, but with your stub, it will! So you'll have passing tests despite the non-working code!
Here's another example that makes another case for dependency injection. Say I have the following function:
function getDayOfWeek() {
var date = new Date();
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
return dayNames[date.getDay()];
}
This getDayOfWeek function is dependent on date. This would be a nightmare to test since we have no control over date's value. If we rewrite this function with a way to supply a date value (i.e. inject the dependency), we can check test the function for any fixed date easily:
function getDayOfWeek(date) {
date = date || new Date();
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
return dayNames[date.getDay()];
}
assertEqual('Wednesday', getDayOfWeek(new Date(2015, 0, 1)));
assertEqual('Thursday', getDayOfWeek(new Date(2015, 0, 2)));
// and so on...