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);
Related
This question already has answers here:
Remove everything after a certain character
(10 answers)
Closed 2 years ago.
After fetching data from api, sometimes it return data as
Date: "2020-09-10T13:21:08Z"
or sometimes as
Date: "2020-05-18T10:11:08Z"
Is there any way to remove the characters after T so output can be in yy/mm/dd format like 2020-05-15 only. Date is dyanimic and does not return same all the time. I also want to change the date as 2020/05/16 using "/" instead of "-"
One way to do this might be to do a simple split() on the T character, and only taking the first segment:
var dateAndTime = "2020-05-18T10:11:08Z";
var date = dateAndTime.split('T')[0];
console.log(date);
In a similar text manipulation vein, it'd also be possible to do something similar using RegExp, which might be helpful if you'd like to stick with the pure text manipulation methodology, but the rules by which you're manipulating the date text could become slightly more complex in the future:
var dateAndTime = "2020-05-18T10:11:08Z";
var date = /\d{4}-\d{2}-\d{2}/g.exec(dateAndTime)[0];
console.log(date);
If you are always receiving the string in the format shown above you can use the split method and then first element of the array will represent the date part.
"2020-05-18T10:11:08Z".split('T')[0]
You could also leverage the Date API to get the same result, which is sometimes a bit cleaner and easier to extend in the future should your requirements change to more complex date-related manipulation:
var dateAndTime = "2020-05-18T10:11:08Z";
var dateAndTimeObject = new Date(dateAndTime);
var date = dateAndTimeObject.getFullYear() + "-" + (dateAndTimeObject.getMonth() + 1) + "-" + dateAndTimeObject.getDate(); // add 1 to getMonth() result to change from month index to proper numerical month representation
console.log(date);
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").
I got the date in ISOFormats and time in 12hrs format. i need to combine togeather and get the output in ISOFormat using javascript. Im doing this in reactJs so using external libraries is fine
date = "2019-02-19T00:00:00.000Z"
startTime = "04.42PM"
outputDateTime = "2019-02-19T11:12:37.680Z"
Have a look at momentjs parse function.
Use it to convert the dates to moment objects and directly add them using the add function.
Example here
If you go pure vanilla I think this is fairly simple (AFAIK you only need hours and minutes and the zone is always fixed, if not, upgrade).
var yourDate = "2019-02-19T00:00:00.000Z";
var yourTime = "04.42PM"
var dat = yourDate.split("T")[0];
var minutes = yourTime.split(".")[1].slice(0,2);
var isPm = yourTime.split(".")[1].slice(2) === "PM";
var hours = isPm ? parseInt(yourTime.split(".")[0]) + 12 : yourTime.split(".")[0];
var date = new Date(dat+ "T" +hours+":"+minutes+":00Z");
Basically, I decomposed the input strings into interesting parts, compensated for PM if needed and put them back together :)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
How do I trim javascript date object returned as 01/26/2012 into 1/26/2012?
it could be applicable for both month or days.
So 01/01/2012 should be trimmed as 1/1/2012.
Regular expression? jquery trim function? I am not sure how to go on this?
var date=date.replace(/^0+/, '');
or
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
For a simple string operation, a RegEx can be used:
date = date.replace(/\b0(?=\d)/g, '')
If it is indeed a date object format it.
Quick example (See it in action):
var today = new Date();
var today_string = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
alert(today_string);
Either way, this is not a good use of regular expressions.
Convert to a Date object first.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Javascript doesn't have built-in formatting functions for dates, but there are a lot of simple libraries that serve this need. Personal favorite: http://blog.stevenlevithan.com/archives/date-time-format