How to Get Formatted Date String In React Native - javascript

In many apps we can see the date formatting like this.
If it's today, then print hh:mm,
If it's yesterday, then print yesterday,
If it's in this week, then print day of week, (ex, Wednesday)
If it's in this year, then print MM/dd
else print YY/MM/dd
Something like this.
How can I implement in React Native or javascript?
Is there library for this?

Use library momentjs. There is function isSame which compare given date with year,month or day. Like
moment().isSame('2010-01-01', 'year'); // true
moment().isSame('2011-01-01', 'month'); // false, different year
moment().isSame('2010-02-01', 'day'); //
moment().isSame('2010-02-01', 'week'); //
In your case, 1st on
const dateString = moment().isSame('2018-01-01', 'day') ? moment('2018-01-01 5:55').format('hh:mm') : else check for other condition
Better go from year to month to week and week to day.

Related

Get Day of The Week from Date Range in Javascript

how do I save the day of the week to array from a given date range. For example, from 8/23/2021 to 12/11/2021, I would like to get the dates that are Mondays and save these dates to an array? Thanks
So you can use the getDay method.
Given your date:
var someday = new Date('8/23/2021');
using the getDay against the someday will return the day of the week index. 1 in this case.
Edit (Side-note): Looks like Sunday is the start of the week for JS
We can pass some options to get the proper long day and formatting.
var long_day = new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(someday);
This will return, Monday. You could save it when its 1/Monday, up to you.
JSFiddle

Moment date is working in Chrome not working in Firefox

I am allowing the user to add a date manually in the date field.
If the user enters the date as 1/1/13 I am expecting a result as 01/01/2013.
This is what I am using.
Code:
moment("1/1/13").format('MM/DD/YYYY')
In chrome it is working fine but not working in FF and IE it shows 01/01/1913 instead of 01/01/2013.
Fiddle
You need to give moment the format of the data it's parsing, using moment(string, string). In fact, if you look in your web console, moment is telling you that:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
So:
moment("1/1/13", "M/D/YY").format("MM/DD/YYYY");
// ^^^^^^^^^^----- the format to parse with
...assuming the date is in month/day/year order (since that's what you're outputting).
Example (I've changed the date slightly so we can tell days from months):
console.log(moment("1/2/13", "M/D/YY").format("MM/DD/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
In a comment you've said:
I am allowing them to add mm/dd/yyyy and mm/dd/yy format. this is not working for 1/1/1999
See the docs linked above, if you want to support a variable number of digits in the year, use YYYY for the year:
console.log(moment("1/2/13", "M/D/YYYY").format("MM/DD/YYYY"));
console.log(moment("1/2/1999", "M/D/YYYY").format("MM/DD/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
This is because Moment.js uses the Date object when creating a new moment, and unfortunately that works differently in Firefox and Chrome.
To test it simply try creating a new date in both browsers.
new Date('1/1/13');
Frankly, I am surprised that Chrome interprets this as 2013. To be safe and cross-browser compliant, just write out the full year. If you are getting this from an outside source, you should simply be able to parse it and reformat it to a safer shortened ISO format like so:
dateString.replace(/^(\d\d?)\/(\d\d?)\/(\d\d{2,4})$/, (day, month, year) => {
day = day.length === 1 ? '0' + day : day;
month = month.length === 1 ? '0' + month : month;
year = year.length === 2 ? '20' + year : year;
if (year.length === 3) {
throw new Error('Invalid date format. Year must either be 2 or 4 characters long.);
}
return [day, '-', month, '-', year].join('');
};
It's working perfectly in Chrome and Mozilla
moment(`${day}/${month}/${year}`, "DD/MMM/YYYY").format("MMMM/DD/YYYY");
//January/01/2021

Momentjs firstday of week

I am using momentjs. I would like to change the first day of week to Monday and somehow it works.
moment.locale('en', {
week : {
dow : 1 // Monday is the first day of the week
}
});
If I type moment().startOf('week').format('dddd DD-MM-YYYY'), it Shows
"Monday 19-01-2015"
But if I type moment().year(2014).week(4).day(0), it will shows as
"Sunday 18-01-2015"
Anyone knows why it got this issue?
The day function is not locale aware. it always uses Sunday as day 0.
Use the weekday function instead - which is locale aware.
See the docs for day and weekday, which explain this pretty well.

Date to epoch and vice versa - JavaScript

I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

how can you figure out the week from a single date

I am building a project and in that project the user is going to input a date eg. 8/2/2011. then i am going to show them the information for the week that contains 8/2/2011. How can you figure out which week to show? for this project i am using javascript, jquery, and php.
You should be able to do what you want by getting the first day of the week the given date occurs in.
If your weeks start on Monday:
Date.prototype.lastMonday=function(){
var d= new Date(this), weekstart= 1;
while(d.getDay()!== 1) d.setDate(d.getDate()-1)
return d;
}
alert(new Date().lastMonday())
//returns the current date if does fall on a Monday
If you want to know the days that compose the week you can just find out the day of the week and show the appropriate days before and after. To know the day of the week just use the getDay method of the Date object(see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getDay). For more info on the Date object see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date.

Categories

Resources