i wanted to ask if someone knows how to remove the Day Name from the following example,the alert returns Sat Feb 29 2020, im not using Moment.js only Jquery because i only need to be able to handle the date in the format that is written below as code.
var mydate = new Date('29 Feb 2020');
alert(mydate.toDateString());
Thank you for reading this question and hope i make clear what my problem is
The Date#toDateString method would result always returns in that particular format.
So either you need to generate using other methods available or you can remove using several ways,
1. Using String#split, Array#slice and Array#join
var mydate = new Date('29 Feb 2020');
// split based on whitespace, then get except the first element
// and then join again
alert(mydate.toDateString().split(' ').slice(1).join(' '));
2. Using String#replace
var mydate = new Date('29 Feb 2020');
// replace first nonspace combination along with whitespace
alert(mydate.toDateString().replace(/^\S+\s/,''));
3. Using String#indexOf and String#substr
var mydate = new Date('29 Feb 2020');
// get index of first whitespace
var str = mydate.toDateString();
// get substring
alert(str.substr(str.indexOf(' ') + 1));
If you've got a Date object instance and only want some parts of it I'd go with the Date object API:
mydate.getDate() + ' ' + mydate.toLocaleString('en-us', { month: "short" }) + ' ' + mydate.getFullYear()
Just keep in mind the functions are local time based (there are UTC variants, e.g. getUTCDate()), also to prevent some confusion getMonth() is zero-based. Working with dates in JavaScript is where the real fun begins ;)
The toLocaleString function is relatively new though (IE11+), check other possibilities if you need to support older browsers.
Proper way is to use DateTimeFormat. You can play around by manipulating the format object inside DateTimeFormat.
let myDate = new Date('29 Feb 2020');
let formattedDate = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "short",
day: "2-digit",
}).format(myDate);
alert(formattedDate)
Easiest way is to replace all alpha characters from a string. That way you will not make mistake once day name is in a different position.
var withoutDay = '29 Feb 2020'.replace(/[a-zA-Z]{0,1}/g,'').replace(' ', ' ');
alert(withoutDay);
Code replace(/[a-zA-Z]{0,1}/g,'') will replace all alpha characters from string and replace(' ', ' '); will remove double spaces.
I hope this helps.
Related
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 1 year ago.
I'm stucked on javascript.
I get thi example string from JSON :
Saturday 14th August
How can i convert it in
14/08/2021
Thanks.
You can do it with Pure Javascript with much more logic. My suggestion is to use Moment.Js It's a really easy way to handle complex DateTime data.
Check this working code:
const dateString = "Saturday 14th August";
const formattedDate = moment(dateString, "dddd Do MMMM").format("DD/MM/Y");
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
NOTE:
As #svarog mentioned in the comment, It's hard to find the year, If it's not provided. But the common practice is getting the current year. Moment JS handles this very well.
let jsonDateString = "Saturday 14th August"
//this is the string you get
let jsonDateStringArray = jsonDateString.split(" ");
//here we split the words so we can better manipulate them
let month = jsonDateStringArray[2];
//we save the month here
let day = jsonDateStringArray[1].replace(/\D/g, "");
//saving the day and removing everything but numbers
let year = new Date().getFullYear();
//creating a date so we can get the year without having to hardcode it
let completeDate = new Date(Date.parse(month + ' ' + day + ', ' + year));
//create a new date from the string we pass 'August 14, 2021'
console.log(completeDate.toLocaleDateString('en-GB'));
//parameter en-GB for 14/08/21, without parameter we get 08/14/2021
I wanted to convert a timestamp which i am getting as below format
"2019-08-31T00:00:00+0800"
when i am converting into date using javascript it is giving me
Fri, 30 Aug 2019 16:00:00 GMT
But the desired date is
31 Aug 2019
I have noticed that there is +0800 at the end of the timestamp, if i add that time to the GMT time, it is giving me the desired result.
Is there any method or a date function to convert it. or do we have any angular pipes to convert it into the desired date ?
which format of date is it actually ?
can refer to this link for GMT +8 offset - https://greenwichmeantime.com/time-zone/gmt-plus-8/
For dates and time it is easier to work with Moment, so you can use the format function:
Moment Format
Or use the toLocaleDateString function:
toLocaleDateString Prototype
So you can do this:
var options = {year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('en-EN', options));
Will give you this:
"December 20, 2012"
You can play with the options to get the wanted result.
Or you could use date-fns which is more modular. https://date-fns.org/. You can import only the parts of date-fns that you use. Moment is big
You could try something like this. It is no function, it's a crude way. You can check it out if it works for you. Try with all the different cases to verify.
var this_date = '2019-08-31T00:00:00+0800'
var date = new Date(this_date).toDateString()
var date_list = date.split(' ');
date = [ date_list[2], date_list[1], date_list[3] ].join(' ')
console.log(typeof date);
console.log(date)
var this_date = '2019-08-31T00:00:00+0800'
var date = new Date(this_date)
console.log(date.toString())
You can as well take a look here, an older stackoverflow post.
You can use it as a function if you like it. If you are looking for something else, Please give the functions you are using for conversion and as well try to find the 'typeof' variable.
Good day everyone!
Working on aprojectmI had to start working with Google Spereadsheet interface and faced a problem I cannot quickly overcome due to not working with JavaScripts ever before.
I have a date in specific format as a string
var date = "2012-08-09";
What I need is to get the next day date as
date = "2012-08-10";
which should include changing not only the day, but month and year too, if necessary.
I've tried using date format
var datum= new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.toString('yyyy-MM-dd');
but the code appears to fail at writing date to datum variable.
What is the best and quickiest way tosolve this litle problem?
Thanks
The problem when you tag a question 'Javascript' and when you are actually using Google Apps Script is that you get nice answers from people that do not know some special functions available in GAS.
GAS is based on Javascript but Javascript is not GAS... if you see what I mean ;-)
That said, there is actually a "special" function to format date string and I'll show it in the following code.
But there is also another point that could put you into trouble : if you don't mention hours in your date object there is a risk to shift one day if you live in a country that uses daylight savings. This issue has been discussed quite often on this forum and elsewhere so I won't give all the details but it's a good idea to take this into account when you play with date objects. In the code below I extract a tz (time zone) string from the date object we have just created to know if it's in summer or in winter time, then I use this tz string as a parameter in the Utilities.formatDate() method . This guarantees an exact result in every situations.
Here is (finally) the test code :
(use the logger to see results. script editor>view>logs)
function test(){
date = "2012-08-9";
var parts = date.split('-')
var datum = new Date(parts[0],parts[1]-1,parts[2],0,0,0,0);// set hours, min, sec & milliSec to 0
var tz = new Date(datum).toString().substr(25,8);// get the tz string
Logger.log(datum+' in TimeZone '+tz)
datum.setDate(datum.getDate() + 1);// add 1 day
var dateString = Utilities.formatDate(datum,tz,'yyyy-MMM-dd');// show result like you want, see doc for details
Logger.log(dateString);// the day after !
}
Logger results :
Thu Aug 09 2012 00:00:00 GMT+0200 (CEST) in TimeZone GMT+0200
2012-Aug-10
It sounds like a parsing problem you may have better luck, splitting out the date and putting the parameters in individually, any errors you get would be useful:-
var parts = date.split("-");
var datum = new Date(
parseInt(parts[0], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[2], 10));
There is no built in formatting function for the JavaScript Date object, I'm not sure if the google apps api is any different though. To perform the last line of your code you may either need to write your own functions to extract the data from the JavaScript date object and format it, hint you will also need to write a zerofill function if you want to ensure two digits in your date and month parts of the output.
var formatted = datum.getFullYear() + "-" +
zerofill(datum.getMonth() + 1, 2) + "-" +
zerofill(datum.getDate(), 2);
Passing a format string to toString works in .NET, and it may work in Java, however this doesn't work in Javascript.
Try the following,
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
Try the following in http://jsfiddle.net/ It works.....
<html>
<head>
<script>
function foo(){
var date = "2012-08-09";
var datum = new Date(date);
datum.setDate(datum.getDate() + 1);
date = datum.getFullYear() + "-" + (datum.getMonth() + 1) + "-" + datum.getDate();
document.getElementById("demo").innerHTML = date;
}
</script>
</head>
<body onload="foo()">
<p id=demo></p>
</body>
</html>
I've inherited a project for a company I'm working for. Their dates are recorded in the following format:
March 18th, 2011 would be listed as "18 Mar 2011".
April 31st, 2010 would be listed as "31 Apr 2010".
How would I use Javascript to add one day to a date formatted in the above manner, then reconvert it back into the same format?
I want to create a function that adds one day to "18 Mar 2011" and returns "19 Mar 2011". Or adds 1 day to "30 Jun 2011" and returns "1 Jul 2011".
Can anyone help me out?
First of all there is no 31st of April ;)
To the actual issue, the date object can understand the current format when passed as an argument..
var dateString = '30 Apr 2010'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); // create new increased date
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).substr(-2) + ' ' + newDate.toDateString().substr(4,3) + ' ' + newDate.getFullYear();
alert(newDateString);
demo at http://jsfiddle.net/gaby/jGwYY/1/
The same extraction using (the better supported) slice instead of substr
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).slice(-2) + ' ' + newDate.toDateString().slice(4,7) + ' ' + newDate.getFullYear();
Demo at http://jsfiddle.net/jGwYY/259/
You would want to convert the date string into a Date object, add one day to the object, and then convert back. Please have a look at the API docs for Date as a starting point.
Most (all?) browsers will be able to parse that date string in with a simple
var parsedDate = new Date(dateString);
Once you have a Date object you can add a day and output a formatted date string using something like underscore.date.
If you discover that some browsers can't parse that date format then you can write a pretty simple regex that will pull apart the date string into its constituent parts, and then build a Date instance by hand.
Also I would strongly recommend doing the parsing in a separate function, and to try and keep dates in a Date representation as much as possible. Parse the string into a date as soon as you can, and format it back into a string as late as you can.
How does one convert a string of a date without a year to a JS Date object? And how does one convert a date string with a year and a time into a JS Date object?
Many different date formats can be converted to date objects just by passing them to the Date() constructor:
var date = new Date(datestring);
Your example date doesn't work for two reasons. First, it doesn't have a year. Second, there needs to be a space before "pm" (I'm not sure why).
// Wed May 27 2009 23:00:00 GMT-0700 (Pacific Daylight Time)
var date = new Date("2009/05/27 11:00 pm")
If the date formats you're receiving are consistent, you can fix them up this way:
var datestring = "05/27 11:00pm";
var date = new Date("2009/" + datestring.replace(/\B[ap]m/i, " $&"));
I'd use the Datejs library's parse method.
http://www.datejs.com/
I tried your example and it worked fine...
5/27 11:00pm
Wednesday, May 27, 2009 11:00:00 PM
I have used the Dojo time parser to do things like this:
Check it out:
http://api.dojotoolkit.org/jsdoc/HEAD/dojo.date.locale.parse
Not the cleanest, but works:
var strDate = '05/27 11:00pm';
var myDate = ConvertDate(strDate, '2009');
function ConvertDate(strWeirdDate, strYear)
{
strWeirdDate = strWeirdDate.replace(/ /, '/' + strYear + ' ');
return new Date(strWeirdDate);
}
Probably want to trim the string first as well.
Just another option, which I wrote:
DP_DateExtensions Library
It has a date/time parse method - pass in a mask and it'll validate the input and return a data object if they match.
Also supports date/time formatting, date math (add/subtract date parts), date compare, speciality date parsing, etc. It's liberally open sourced.