Moment.JS - Get date from week number - javascript

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.

Related

unable to get the date format

I'm trying to change the date format in javascript where in a variable i m getting the date value like this "11/09/2019" and want to change in a format like this "11-09-2019".but somehow i'm getting this format "sat nov 09 2019" whereas it should be "tue sep 11 2019".
can anyone help me. any help would be appreciated.
var alt_date1 = "11/09/2019";
var date = new Date(alt_date1);
alert(date);
output: Sat Nov 09 2019 00:00:00 GMT+0530 (India Standard Time)
If I understand your question right, you want a different format i.e., "-" instead of "/" and you're also getting the wrong date? 2 days ahead? Depending on your environment (browser, node, etc) the Date API can behave differently. I think this link might help you: JavaScript's getDate returns wrong date (Not sure though, some answers pertain to the time zones it uses)
As for formatting look here:
https://codehandbook.org/javascript-date-format/
Example from that site:
let current_datetime = new Date()
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
console.log(formatted_date)
// output
"19-10-2018"
It's a little bit tricky to understand the question fully, but if you don't need a Date object, and you want to just format the string as 11-09-2019 it can be achieved with the simple replace function like this:
alt_date1.replace(/\//g, '-')

Convert a time stamp in javascript which is having a time period (+0800) to be added in it's end

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.

moment.js uses the month as day instead the day

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')

Adding one day to Javascript date + unique formatting?

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.

Javascript convert "05/27 11:00pm" to date?

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.

Categories

Resources