I have a date field coming from SQL as follows:
2022-06-30T00:00:00.000Z
Im trying to get the first 10 characters (date in format yyyy-mm-dd) from it, but I can't get it to work.
First, I tried a "left" function
textPaidThru= pt.slice(0,10)
And I got
Wed Jun 29
Then I tried moment
let textPaidThru = moment(paidThru).format('YYYY-MM-DD');
But Im getting this:
2022-06-29
No matter which method I try to use, I always get the provided date minus one day.
I encounter working with dates very hard in JS. Is there a way to get the date part only as provided by SQL? This is the value Im expecting:
2022-06-30
Thanks.
TL;DR; Timezones
Actual Answer
You could just use some vanilla javascript and parse it like this:
Note month is zero index in Date, so you will need to add 1 to each:
const dateToParse = "2022-06-30T00:00:00.000Z"
let parsedDate = new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth()+1}-${parsedDate.getDate()}`
console.log(formattedDate)
The reason you are getting 6-29 is most likely due to you not living in UTC+0. I get 6-29 as well, but that is because I live in UTC-7.
If you look in the code below I change the time to be UTC-7 (which should work for your timezone as well if what your profile says is correct UTC-3) and the console log for me displays 6-30 now.
const dateToParse = "2022-06-30T07:00:00.000Z"
let parsedDate = new Date(dateToParse)
const formattedDate = `${parsedDate.getFullYear()}-${parsedDate.getMonth()+1}-${parsedDate.getDate()}`
console.log(formattedDate)
If you know you'll always get the same format (well, you probably will), you can just use split, something like.
let dateTime = '2022-03-25T02:03:04.000Z';
let onlyDate = date.split('T')[0];
This will split the string at T and you basically only want the first part (array index 0) and that's it.
Related
I have a strange problem I dont quite understand.
Why moment will use strange timezone (+01:45) by default and not using the
one I provided in input string?
I propably don't correctly understand how moment works or I am missing something very basic.
I tried testing and found out I need to use parseZone() by just experimenting with different options. I don't know if its the correct way to solve problem where I need get the same date out of moment I put into it.
If I use any timezone +01,+02 or +03(my current)
in moment input string I get previous date and strange time/timezone.
For +00:00 it will work, but I cannot choose this timezone since its the timezone I get from a service.
moment("1800-01-01T00:00:00.000+03:00").format() =>
1799-12-31T22:39:49+01:45
but
moment("1800-01-01T00:00:00.000+03:00").parseZone().format() will give corrent output
1800-01-01T00:00:00+03:00
This is when I live in +03:00 GMT (Summer time).
Colleagues who live in +02:00 (Summer time too) get correct results (and most of you will propably too)
My results of below javascript sandbox are:
1799-12-31T22:39:49+01:45
1800-01-01T00:00:00+03:00
I use google chrome (100.0.4896.127 64-bit) and
my locale in windows 11 is Finnish / Finland (up to date).
import "./styles.css";
var moment = require("moment");
let checkDate = moment("1800-01-01T00:00:00.000+02:00");
//checkDate = checkDate.utcOffset(0, true);
// let fixedDate = checkDate.add('minutes',checkDate.utcOffset());
document.getElementById("app").innerHTML = checkDate.format() + "<br>";
document.getElementById("app").innerHTML += checkDate.parseZone().format();
Tests
I'm not sure if this is going to be a duplicated question as I couldn't find anything on SO therefore, I'm going ahead with this question -
I have a date string which is locale-dependent and I have the locale info with it too.
Eg. dateStr = '06/07/2021' and locale='en-GB'.
How do I get a JS Date object from this? The Date constructor doesn't seem to take a locale and by default parses it with respect to the en-US locale(MM-DD-YYYY).
By this I mean, that the above dateStr will be converted to 7th June 2021 and not the actual 6 July 2021 using the Date constructor.
UPDATE:
I got something from d2l-intl but it doesn't work. Quite strange.
var parser = new d2lIntl.DateTimeParse('en-GB');
var date = parser.parseDate('23/05/2021');
console.log(
date.getMonth(),
date.getDate()
);
which breaks as it still accepts date string in en-US format.
Looking at the question's comments, I believe sometimes people just don't understand the question and start blaming the problem itself. It's ridiculous :D
This may not be the perfect way to go about it (there can be something cleaner and shorter), but this definitely works.
locale = 'en-GB';
value = '07/06/2021';
moment.locale(locale);
const localeData = moment.localeData();
const format = localeData.longDateFormat('L');
console.log(moment(value, format).format('YYYY-MM-DD')); // '2021-06-07'
I am running NodeJS 8 in AWS Lambda and want to timestamp and attach to an S3 the current day, month, year and current time when the function runs.
So if my function was running now, it would output 220619-183923 (Todays date and 6.39pm and 23 seconds in the evening.)
For something a little complex like this do I need something like MomentJS or can this be done in pure Javascript?
Eventually this will make up a S3 URL such as
https://s3.eu-west-2.amazonaws.com/mybucket.co.uk/BN-220619-183923.pdf
UPDATE
The webhook appears to have some date/time data albeit in slightly different formats that weren't outputted in the Lambda function, so these could prove useful here. Can ':' be used in a URL and could the UTC which I assume is in milliseconds be converted into my desired format?
createdDatetime=2019-06-22T18%3A20%3A42%2B00%3A00&
date=1561231242&
date_utc=1561227642&
Strangely, the date_utc value which is actually live real data. Seems to come out as 1970 here?! https://currentmillis.com/
You don't need moment. I have included a solution that is quite verbose, but is understandable. This could be shorted if needed.
Since you are using S3, you might also consider using the UTC versions of each date function (ie. .getMonth() becomes .getUTCMonth())
Adjust as needed:
createdDatetime= new Date(decodeURIComponent('2019-06-22T18%3A20%3A42%2B00%3A00'))
date=new Date(1561231242 * 1000);
date_utc=new Date(1561227642 * 1000);
console.log(createdDatetime, date, date_utc)
const theDate = createdDatetime;
const day = theDate.getUTCDate();
const month = theDate.getUTCMonth()+1;
const twoDigitMonth = month<10? "0" + month: month;
const twoDigitYear = theDate.getUTCFullYear().toString().substr(2)
const hours = theDate.getUTCHours();
const mins = theDate.getUTCMinutes();
const seconds = theDate.getUTCSeconds();
const formattedDate = `${day}${twoDigitMonth}${twoDigitYear}-${hours}${mins}${seconds}`;
console.log(formattedDate);
UPDATE based upon your update: The code here works as long as the input is a JavaScript Date object. The query parameters you provided can all be used to create the Date object.
You can definitely use MomentJS to achieve this. If you want to avoid using a large package, I use this utility function to get a readable format, see if it helps
https://gist.github.com/tstreamDOTh/b8b741853cc549f83e72572886f84479
What is the goal of creating this date string? If you just need it as a human-readable timestamp, running this would be enough:
new Date().toISOString()
That gives you the UTC time on the server. If you need the time to always be in a particular time zone, you can use moment.
This is my data format:
"21/03/2019 19:18"
The problem i am facing is, when ever if i am dealing with date or time there is an issue with the month ( it has 03 instead of 3 ). I am using library called date-fns. And also i have tried with the help of javascript date objects without using library, but no luck still the month should not have zero in-front of it.
So, how to remove the "0" in-front of "3", and one more problem is how to do this conditionally , because when its Dec, i will be getting data as "21/12/2019 19:18". So, in this case , i should not remove "1" as its located in same position of "0" in previous scenario.
In other words, i want to remove "0" by checking if there is "1" presented in that position or index, if presented then remove else remove "0"
How to achieve this.
I tried the below code:
const d = new Date(2019,03,21)
But, its says legacy error. So when i removed "0" infront of "3" it works fine. Please help
I assume you get the data back as a string and you just want to remove leading zeros from the 2nd number only?
we can use .split to break up the string into parts, and then we can use parseInt to convert some string parts into numbers. that will turn the string "03" into the number 3
function removeleadingZerosFromDateString(str) {
//Break up the date string on the slashes and whitespace, so we have an array of all the parts
var parts = str.split(/\/|\s/);
console.log(parts);
//Assign each array item to a variable so we can see what is what
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parts[2];
var time = parts[3];
var meridian = parts[4];
return day+'/'+month+'/'+year+' '+time+' '+meridian;
}
var result = removeleadingZerosFromDateString("21/03/2019 19:18 PM");
console.log(result);
You said you were using date-fns, so I'll give an answer in that regard.
The current 1.x version doesn't support parsing strings in a custom format, but they are adding that to 2.x, and you can use the alpha release to try it today.
The syntax is:
var date = parse(dateString, formatString, baseDate, [options]);
See the documentation for the parse function in version 2.0.0-alpha.27.
In your case, it would be like this:
var date = parse("21/03/2019 19:18", "MM/dd/yyyy HH:mm", new Date());
Lastly, if you want to use a library for this but don't want to experiment with an alpha, you can either wait for Date-fns 2.0 to become final, or you can try Luxon or Moment - both of which already have this functionality (though Moment uses a slightly different token format "MM/DD/YYYY HH:mm").
Using the moment.js library say i have a datetime with today's date and i would like to replace only the date part of the datetime with another value and keep the time portion the same
I don't want to subtract or add days etc - i have a 3rd party time picker that when you select a time it creates a datetime that is always the current day. I need to send back to server a different datetime - the date is different but keep the time portion from the picker.
example code:
let myDate = "2019-03-15T00:00:00"
let selectedDateTime = "2019-04-04T12:30:00"
expected result would be:
"2019-03-15T12:30:00"
Thank you
The following should solve your problem:
let myDate = moment("2019-03-15T00:00:00")
let selectedDateTime = moment("2019-04-04T12:30:00")
selectedDateTime.date(myDate.date());
selectedDateTime.month(myDate.month());
selectedDateTime.year(myDate.year());
As #JeremyThille suggested, you should take a look at the documentation.