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.
Related
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.
I don't see this in the documentation of moment.js. Maybe I'm skipping over it but I want to convert a week number in a year to a date format.
for example
week: number = 13
year: number = 2017
date: date = // get date format for the first day of that week
I'm using moment.js, but I can't find what I want in the documentation. Is this possible to do? I've found some answers for plain javascript, but since I'm already using moment.js, I figured there might be an easy way to do this
Yes, it's possible:
var date = moment('2017').add(13, 'weeks');
Note that moment('2017') returns January 1st of 2017.
Using startOf('isoweek') you will get the first day of the week.
moment('2017').add(13, 'weeks').startOf('week').format('DD MM YYYY'); // "02 04 2017"m, gives you Sunday(last day of the week)
moment('2017').add(13, 'weeks').startOf('isoweek').format('DD MM YYYY');
"27 03 2017"// first day of the week ( gives you Monday)
No need to add:
moment().year(2017).week(13);
Another way is to use a format string
var dateLocale = moment(week + " " + year, "ww gggg");
var dateISO = moment(week + " " + year, "WW GGGG");
moment.js seems to understand expressions produced by the default HTML input type="week" element, like: 2022-W26.
So you can use moment to convert these expressions into dates, like so:
const weekMoment = moment('2022-W26') // week 26 of year 2022
const weekStart = weekMoment.toDate() // Mon Jun 27 2022 00:00:00 GMT+0100
Like so you do not need to create the date and then add weeks to it. One moment call is enough.
Just another note: for this to work do not forget the pad the week number, e.g: week 1 should be 01, etc. You should always have two digits to represent the week.
I'm using currently moment.js (moment-with-locales.js - v.2.14.1) in my project. I want to remove the time of my datetime string to get only the date. But if I use the .format() method of moment.js I got an incorrect date.
I want to format this datetime string:
from ' 08.10.2016 11:00 ' to ' 08.10.2016 '
Here is a snipped that I used in my angular project:
var date = moment('08.10.2016 11:00').format('DD.MM.YYYY')
console.log(date)
If I run this I got this output
10.08.2016
instead of
08.10.2016
The funny thing is, if I want to get the timestamp (milliseconds) of my datetime string, it works perfect. Example:
var dateStart = moment('08.10.2016 19:00', 'DD.MM.YYYY HH:mm').valueOf()
console.log(dateStart)
Will return
1475946000000 -> Sat Oct 08 2016 19:00:00 GMT+0200
How can I get the correct Date?
It depends on your locale. en-US locate means moment will parse by "month day year". So, you need to parse with the pattern as well:
var date = moment('08.10.2016 11:00','DD.MM.YYYY HH:mm').format('DD.MM.YYYY')
I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013
You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp
31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."
If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.
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.