I'm reading a file's modification date with fs.statSync() and I'd like to compare it with a String that comes from my database:
This is my file's last modification date:
Fri Mar 24 2017 13:22:01 GMT+0100 (Central Europe Standard Time)
And I'd like to compare with this string:
2016-07-18 12:28:12
How can I do this with Node.JS? Can I somehow create a new date from the String?
You can use Moment parse both of those formats and compare the results.
var date1 = moment(string1, format1, true);
var date2 = moment(string2, format2, true);
if (date1.diff(date2) === 0) {
// equal
} else {
// not equal
}
See this answer for parsing dates in different formats:
Check if a string is a date value
Make sure that you parse it with explicit format and you don't let it guess the format, or otherwise you will never be sure if it guessed correctly.
Related
I have the database collection as such:
{
data: [
item: {
date: "2022-03-22T08:10:37.023Z"
},
item: {
date: "2022-03-22T08:11:04.023Z"
},
...
]
}
I also have variables start_date and end_date which are momentjs dates. I can compare dates with isAfter() and isBefore() methods.
How to get all items with date between start_date and end_date?
Note: date: "..." is a string and not ISODate object.
data is an array.
I can also convert the date string to momentjs date for comparison.
looks like your date is in ISO format so the moment constructor should accept it, e.g.
moment(date);
To prove it, convert it into a plain js Date object and print it
moment("2022-03-22T08:11:04.023Z").toDate()
// Tue Mar 22 2022 10:11:04 GMT+0200 (Israel Standard Time)
You may want to look at isBetween
moment(date).isBetween(start_date, end_date);
Will return true if date is between those two moments.
After that you can use something like .filter to remove the data items that are not between your range and that's about it.
I'm successfully fetching some data using Axios and I need to store this data to my Postgres database.
One of the fields from the fetched data is a pubDate field, which is formatted exactly like this:
"Tue, 15 Apr 2020 20:01:30 +0000"
Reading through Moment docs, this seems to be this "locale aware 'llll'" format.
So, what I need is to parse this pubDate and format it as the default Postgres date format. The pubDate would then look something like this:
"2020-04-14T20:01:30"
I've been searching for this process for quite some time and just wasn't able to find anything that would work.
I've tried this (did not work), based on the String + Format from docs:
let date = moment(pubDate, 'llll').format();
I'm new to NodeJS, sorry if I messed up something. Thank you in advance!
Looks like MomentJS doesn't have a default function for this (I couldn't find anywhere), so I've created one:
function parseDate (date) {
// date format: "Thu, 16 Apr 2020 18:29:49 +0000"
date = String(date);
// date format (after , split): ["", "Day", "Abbreviated Month", "Year", "hour:minute:seconds", "+0000"]. I.E.: ["", "16", "Apr", "2020", "18:29:49", "+0000"]
let dateInfo = String(date).split(",")[1].split(" ").slice(1, -1);
// ["Day", "Abbreviated Month", "Year", "hour:minute:seconds"]
let dateString = dateInfo[2] + '-' + moment().month(dateInfo[1]).format("M") + '-' + dateInfo[0] + ' ' + dateInfo[3];
const parsedDate = moment(dateString, 'YYYY-MM-DD hh:mm:ss');
return parsedDate;
}
When I test this code in the browser, it processes dates in a logical way (invalid date), but in NodeJS new Date("12345") creates +012345-01-01T06:00:00.000Z
Here is my test for NodeJS
$ node -e 'console.log(new Date("12345"))'
// outputs: +012355-01-01T06:00:00.000Z
Here you can run it in browser
console.log(new Date("12345"))
// outputs: null
Any idea why this is happening? And how can I avoid this?
It depends on the JavaScript engine. In Firefox, dates after January 1, 10000 (year ten thousand) are apparently considered invalid:
> new Date("9999")
Date 9999-01-01T00:00:00.000Z
> new Date("10000")
Invalid Date
In Chrome (that uses V8, just like Node.js) it works perfectly:
> new Date("10000")
Sat Jan 01 10000 00:00:00 GMT-0800 (Pacific Standard Time)
> new Date("12345")
Mon Jan 01 12345 00:00:00 GMT-0800 (Pacific Standard Time)
So, to answer your question: different JavaScript engines have different limits related to which date is valid and which is not, but in general, having just a sequence of digits in a string makes it think it's January 1st of this year (corrected for a timezone used):
> new Date("2019")
Mon Dec 31 2018 16:00:00 GMT-0800 (Pacific Standard Time)
Also note this. Chrome / Node.js:
> new Date("31")
Invalid Date
> new Date("32")
Thu Jan 01 2032 00:00:00 GMT-0800 (Pacific Standard Time)
Firefox:
> new Date("1000")
Date 1000-01-01T00:00:00.000Z
> new Date("999")
Invalid Date
Apparently, Firefox wants the year to have 4 digits exactly, while Chrome/V8 is more flexible.
Also, seems like Chrome/V8 has different logic parsing dates from "1" to "12" (using them as months) but this is totally different story.
As an answer to how to avoid this issue, you can sort of standardize your value to date conversion like so:
// all of these will produce the same date
const stringDate = "1970-01-01T00:00:12.345Z";
const numberString = " 12345 ";
const number = 12345;
function toDate(value) {
if (typeof value === "string" && /^\d+$/.test(value.trim())) {
value = parseInt(value);
}
return new Date(value)
}
console.log("string date", toDate(stringDate));
console.log("number string", toDate(numberString));
console.log("number", toDate(number));
I'm trying to parse a date string and return the corresponding unix time to midnight at the start of the date in the UTC zone. However, my node.js keeps returning the unixtime at the start of that date in MY timezone.
What am I doing wrong? This should print 1440633600 to the console but it prints a number corresponding to the unix time in my timezone, not UTC.
var moment = require('moment');
var datestring = "August 27 2015";
var unixDate = new Date(datestring);
var myDate = moment.utc(unixDate);
console.log(myDate.format('X'));
"datestring" will not always contain a "Z" at the end (which indicates UTC) but it might sometimes, so I can't just add a "Z" before parsing. There's got to be something I'm missing here...
TL;DR:
var myDate = moment.utc(datestring, 'MMMM DD YYYY');
The explanation:
var unixDate = new Date(datestring); with datestring set to "August 27 2015" will set unixDate to the timestamp corresponding to midnight on August 27 2015 in your time zone.
Subsequently, var myDate = moment.utc(unixDate) sets myDate to a moment object set to that same time. Since you are sending it a timestamp and not a date, it has no reason to adjust for timezone. Since you generated the timestamp based on the time in your timezone, that's what moment sees.
One fix is to change that line to var myDate = moment.utc(datestring, 'MMMM DD YYYY');. Since moment will be getting a string to process rather than a UNIX timestamp, it will select midnight on August 27 2015 in UTC.
I am working with SoupUI a i need to adjust a Date/time (UTC) that i get back in a response to a GMT Date/time. The date that i get back in the respone looks as followes:
2012-11-09T00:00:00+01:00
I would like to convert this to
2012-11-08T23:00:00Z
Unfortunatly i lack Java skils and therefore also Groovy skils to be able to do this on my own. i did a lot o searches on date convertions but until now i was still unable to find what i was looking for. i will keep searching. if i do manage to get the solution then i will post it here.
Assuming there isn't a colon in the timezone portion, I believe this should work:
// Your input String (with no colons in the timezone portion)
String original = '2012-11-09T00:00:00+0100'
// The format to read this input String
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" )
// The format we want to output
def outFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" )
// Set the timezone for the output
outFormat.timeZone = java.util.TimeZone.getTimeZone( 'GMT' )
// Then parse the original String, and format the resultant
// Date back into a new String
String result = outFormat.format( inFormat.parse( original ) )
// Check it's what we wanted
assert result == '2012-11-08T23:00:00Z'
If there is a colon in the TimeZone, you'll need Java 7 for this task (or maybe a date handling framework like JodaTime), and you can change the first two lines to:
// Your input String
String original = '2012-11-09T00:00:00+01:00'
// The format to read this input String (using the X
// placeholder for ISO time difference)
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssX" )