MomentJS - shifts the date by a day after format operation - javascript

To work with one component, I need a unix date, to work with another - a text display of days, months and years. Also, each of them can be changed and the second one must synchronize its date with the first one. Now I'm getting an infinite loop because the format operation always shifts the date for me by one day. Can you please tell me how can I get the correct date??
const formatTime = ({ date, format = DEFAULT_FORMAT }: OwnProps): string => {
const inutc = utc(date);
console.log('inutc', inutc)
const formatted = inutc.format(format);
return formatted
}

Okay, i fixed it by replaced utc() to moment() like this:
const formatTime = ({ date, format = DEFAULT_FORMAT }: OwnProps): string => {
return moment(date).format(format)
}

Related

Issue matching string date to compare with with dates in database?

I am trying to find all users that have a matching birthday stored in the format "1975-01-12T00:00:00.000+00:00"
When I send a date of type String to my route and convert it to a date with new Date(req.body.DOB)
I am getting a date with an additional 4 hours: "1975-01-12T04:00:00.000Z" and a Z at the end.
I am new with dates so not too sure what is going on. How can I convert the string date into a date in the same way it is saved in my database, without the additional 4 hours and Z?
router.post("/api/date", async (req, res) => {
try {
const birthdate = new Date(req.body.DOB) // String as "01-12-1975"
const users = await User.find({
DOB: birthdate,
})
res.status(200).send(users)
} catch (err) {
res.status(400).send()
}
})
Databases typically use iso_8601 date format, which includes timezone. Javascript dates use the system timezone upon instantiation, if you use a format which omits the timezone (like the one you have). This is why there is an offset of 4 (offset from UTC timezone), presumably your server is in Russia or something.
You should convert the string to ISO format before converting to a date object. For example, if you store all birthdays as UTC time (at midnight), then you can just convert it like so:
const dateStr = "01-12-1975"
const [date, month, year] = dateStr.split('-')
const isoStr = `${year}-${month}-${date}T00:00:00.000Z`
const newDate = new Date(isoStr) // 1975-12-01T00:00:00.000Z

Moment Timezone not returning expected result

I might be doing something silly here. But essentially, the time in Lisbon right now is 12:27 PM
but the following returns 14:27 (EU central time)
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment.tz(item.startTime, format, timeZone);
const endMoment = moment(item.endTime, format, timeZone);
return time.isBetween(startMoment, endMoment);
I tried several combinations and I get the wrong answer everytime. For example if I set timeZone to be "Europe/Warsaw" it returns 15:27 whereas it should be 13:27.
EDIT: const currentTime = moment().tz("Europe/London").format() returns the correct time for London. However, the return statement moment(currentTime).isBetween(startMoment, endMoment) still reads "moment(correntTime)" as the local time.
isBetween return boolean . And isBetween runs on date object. You are trying to run on time zone object. which is different from date object
const time = moment.tz("Europe/Lisbon")
const timeZone = "Europe/Lisbon"
const format = "'HH[:]mm'"
const startMoment = moment().subtract(8, 'months').tz(timeZone).format();
const endMoment = moment(new Date()).tz(timeZone).format() ;
console.log("startMoment",startMoment)
console.log("endMoment",endMoment)
console.log(moment.tz(new Date(),"Europe/Lisbon").format())
console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

Convert date and hours/minutes/seconds to correct format javascript

I got date in format '20190702' and hours/minutes/seconds in format '125657'
What is the easiest way to convert it to 07/02/2019, 12:56:57
const time = "125657";
const chuncks = str.match(/.{1,2}/g).join(":"); //12:56:57
What about date?
You can just use substr function to extract a part of string and then combine the parts to form new string
const time = "125657";
const date = "20190702";
const formattedTime = `${time.substr(0,2)}:${time.substr(2,2)}:${time.substr(4,2)}`
const formattedDate = `${date.substr(4,2)}/${date.substr(6,2)}/${date.substr(0,4)}`
console.log(`${formattedDate}, ${formattedTime}`)
The easiest is maybe this:
const time = "125657".replace(/(..?)(..)(..)/, "$1:$2:$3");
const date = "20190702".replace(/(....)(..)(..)/, "$2/$3/$1");
console.log(date, time);
The question mark in the first pattern could serve if the time string could have 5 digits instead of 6. If you are certain you always get 6 digits, you can leave it out.
You can use Moment.js to parse dates, it will accept most formats.
let momentDate = new moment.utc('20190702', 'YYYYMMDD');
console.log("Parsed date: ", momentDate);
let momentDateTime = new moment.utc('20190702125657', 'YYYYMMDDHHmmss');
console.log("Parsed date (with time): ", momentDateTime );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Use Moment.js
You provide pattern along with data.
Here, "hh" means "hours" in pattern.
"use strict";
const moment = require("moment");
console.log(moment("125652", "hhmmss").toDate());
Assuming fixed length input strings of decimal digits, you could do something like this:
const date = "20190702";
const time = "125657";
const formatted_date = date.replace(/(\d{4})(\d{2})(\d{2})/, "$3/$2/$1");
//const formatted_time = time.match(/\d{2}/g).join(":");
const formatted_time = time.replace(/(\d{2})(\d{2})(\d{2})/, "$1:$2:$3");
const formatted_date_time = `${formatted_date}, ${formatted_time}`;
console.log(formatted_date_time);
If the year was 2-digit, you could have used the same exact logic and just add a reverse, but since it's a different length, I advise you a manual composition:
const date = '20190702';
const chunks = date.match(/.{1,2}/g);
const formattedDate = [chunks[3], chunks[2], chunks[0]+chunks[1]].join('/');
console.log(formattedDate)
You may use moment.js library to format your date. In your case, the code may look like:
var time = '20190702,125657';
var formated_time = moment(time, "YYYYMMDD,HHmmss").format('DD/MM/YYYY,HH:mm:ss');

How To Get startDate and endDate from RangePicker from ANTD.DESIGN

i'm working ing a react js project and I'm using antd.design Library to show a RangePicker
what i'm trying to solve is how can i get the start date and the end date from this RangePicker when user select a period
that's my code :
handleChangeDebut =range => {
const valueOfInput1 = moment(range.startDate).format();
const valueOfInput2 = moment(range.endDate).format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}
<DatePicker.RangePicker
style={{ width: "100%" }}
getPopupContainer={trigger => trigger.parentNode}
onChange={this.handleChangeDebut}
/>
the issue is on my handleChange function , i always get the date of the current day
is there any attributes in antd design that give us the startDate and the EndDate Selected ?
Thank you for your precious help .
From the documentation, this is the signature of the onChange function function(dates: moment, moment, dateStrings: string, string), It looks like start and end date are passed as an array in the first param:
handleChangeDebut = (range) => {
const valueOfInput1 = range[0].format();
const valueOfInput2 = range[1].format();
console.log('start date',valueOfInput1);
console.log("end date",valueOfInput2);
}

How to query a timestamp field by year in Feathersjs?

Currently I have a timestamp field with value format like 1479664146607.
What I wanted to do is to get all data with timestamp that has a year of let's say 2017.
My current code is non-performant. It gets all the data, and then uses a filter method.
Let's say I got 2000+ records.
const records = []; // all records
const data = records.filter(r => new Date(r).getYear == '2017');
While this code works, it kills the server.
My database is nedb and using feathersjs, I can actually get equality items by
app.service('messages').find({
query: {
timestamp: '2017'
}
});
This code will not work because it will search for the exact year. I am looking for a way to convert the timestamp field to a year before searching it in the database.
Okay, so what I did is to use the $gt and $lt operators.
Let's say we want to get all data in year 2018.
Using momentjs, I did something like this:
const year = '2018';
// Get previous year based on given year
const previousYear = moment(year, 'YYYY').subtract(1, 'year').format('YYYY');
// Get next year based on given year
const nextYear = moment(year, 'YYYY').add(1, 'year').format('YYYY');
// get full ending date of previous year
const endOfPreviousYear = moment(previousYear, 'YYYY').endOf('year').format('x');
// get full starting date of next year
const startOfNextYear = moment(nextYear, 'YYYY').startOf('year').format('x');
// get data where year is greater than `endOfPreviousYear` and less than `startOfNextYear`
const yearQuery = {
$gt: +endOfPreviousYear,
$lt: +startOfNextYear
}
app.service('messages').find({
query: {
timestamp: yearQuery
}
});

Categories