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").
Related
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.
I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);
how can I remove the time after converting a date to ISO String?
var now = new Date();
console.log( now.toISOString() );
if the output is
2017-10-19T16:00:00.000Z
I just want it to be :
2017-10-19
One simple but robust approach is to split along the date separator:
new Date().toISOString().split('T', 1)[0] // => '2019-03-18'
If working with an ISO string of unknown origin, using a Regex pattern as the splitter may prove more reliable (ie. Postgres uses a whitespace as the separator).
const isoString = '2019-01-01 12:00:00.000000'
isoString.split(/[T ]/i, 1)[0] // => '2019-01-01'
Unlike using substring, this approach does not make assumptions about the length of the date (which might prove false for years before 1000 and after 9999).
There are actually many ways to do so:
1- Use Moment JS which gives you kind of flexibility in dealing with the issue
2- The simple way to do it in native JS is to use substring() function like that:
var date = new Date();
console.log(date.toISOString().substring(0,10));
The second way would be more effective if all you need is to remove the time part of the string and use the date only.
Here's how it would be done with momentjs
var currentDate = moment().format('YYYY-MM-DD');
Check out the Jsfiddle link: https://jsfiddle.net/cgbcc075/
It's better to use moment in js for date time related functions. Instantly now you can use substring method:
var a = "2017-10-19T16:00:00.000Z"
a = a.substring(0,10)
The easiest way is just to use split
var now = new Date();
console.log(now.toISOString().split('T')[0]);
Computationally fastest way (ie: no unnecessary allocations) would be slicing up to index 10, since ISO8601 timestamp strings have these elements guaranteed, at least for the years 0000 to 9999.
let currentDate = new Date().toISOString().substring(0,10);
I have this date parsed from an api as a string:
DD-MM-YYYY but sometimes the date is DD-M-YYYY or even D-M-YYYY.
For example:
4-1-2013
or
10-10-2013
or 7-4-2013
The year is always 4 digits but days or months sometimes get one digit. How can I manually (with JS) add 0 in front of a every single digit ?
I am using moment.js for some calculations thus I am remove the '-' using
date.replace("-", "")
to get a whole number (eg. 4-1-2013 = 412013) so I can use it with moment.js but if its a single digit, it all gets messed up.
You can normalise your strings first like this:
date = date.replace(/\b(\d{1})\b/g, '0$1');
which will take any "word" that is just a single digit and prepend a zero.
Note that to globally replace every - you must use the regexp version of .replace - the string version you've used only replaces the first occurrence, therefore:
date = date.replace(/\b(\d{1})\b/g, '0$1').replace(/-/g, '');
will do everything you require.
Moment.js supports formats with dashes, so you don't even need to do any string handling.
moment('4-1-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 04012013
moment('10-10-2013', 'MM-DD-YYYY').format("MMDDYYYY"); // 10102013
If the date variable is in a String format(for example from input[type=date]) then you need to split the data component into single items.
date = date.split('-');
then check both the day's and the month's length
day = date[0].length==1 ? "0"+date[0] : date[0];
month = date[1].length==1 ? "0"+date[1] : date[1];
then get them back together into a format that you desire
date = ""+day+month+date[2];
Working example: http://jsfiddle.net/dzXPE/
var day = new Date();
day = day.getDay();
if(day.toString().length <= 1) {
day = '0' + day;
}
You can use the same for month. I'm not entirely sure you need to convert to string but it wouldn't hurt.
I have 2 dates and I one to check if one date comes before another one.
I know you have to parse the date to a JS date object and then check it with milliseconds.
But the problem is, in my database dateTimes are stored like this.
10-mei-2012 09:36
So my question is how can I compare two of these dates and check that date 1 comes before date2? Oh and for the record, I am also using jquery to get these values.
var dateB = $('#DATUM_BEGIN').val();
var dateE = $('#DATUM_EINDE').val();
kind regards
Stef
In that format you can compare strings as-is, it is safe. So use just
if (dateB < dateE) ...
http://www.datejs.com/ could be helpful. it is a jquery Plugin to compare Dates.
The format you show is "mostly" ISO-8601 combined-date format which is by design comparable as plain text.
The only difference between what you have and pure ISO-8601 is that there would need to be a 'T' where the space character is.
http://en.wikipedia.org/wiki/ISO_8601
So, if you can sort the strings you know which one comes first.
Here's a function found while googling that converts MySQL DATETIME to a JS Object
function mysqlTimeStampToDate(timestamp) {
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
Here's one example of how to use it:
$(function(){
var dateB = mysqlTimeStampToDate($('#DATUM_BEGIN').val());
var dateE = mysqlTimeStampToDate($('#DATUM_EINDE').val());
if(dateB < dateE){
// dateB is older
} else {
// dateB is newer
}
});