Getting today's date from a specific date format in React - javascript

I would like to get today's date with the format below in React:
"2019020420"
I am able to get the current date with this function. How do I modify this such that it will give me the above date format?
getCurrentDate() {
var tempDate = new Date();
var date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
const currDate = date;
return currDate;
}

You can use template literals.
let formatTwoDigits = (digit) => ("0" + digit).slice(-2);
var tempDate = new Date();
var date = `${tempDate.getFullYear()}${formatTwoDigits(tempDate.getMonth()+1)}${formatTwoDigits(tempDate.getDate())}${formatTwoDigits(tempDate.getHours())}${formatTwoDigits(tempDate.getMinutes())}${formatTwoDigits(tempDate.getSeconds())}`;
console.log(date);
However, implementing date formatting by ourselves sometimes could be tedious. If you don't mind using a library, you can take a look at moment.js and its format functions. Moment.js is a commonly used JS library for parsing, manipulating, and formatting dates.

try this library for formatting date in your desired format.
https://date-fns.org/

use moment.js from https://momentjs.com/
Take a look at there first few examples for how to use it for reformatting dates.

Related

Need to transform timestamp to mm/dd/yyyy format

I have a date value in my React app that's returned from MySQL as a string in this format:
"2012-03-04T00:00:00.000+00:00"
The date gets transformed, using moment, to this format:
03/04/2012
Using moment, this is simple:
moment(myDate).format('MM/DD/YYYY')
But I'd like to change this, since moment is no longer maintained.
Is there a simple way to do this transformation with some built-in javascript date function?
The answers here and here don't help here, as they include no details on formatting the resulting date the way I need it.
You can use this:
const date = new Date("2019-08-01T00:00:00.000+00:00")
const year = date.getFullYear().toString().padStart(4, '0')
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
const formatted = `${month}/${day}/${year}`
console.log(formatted)
But I would just another library like date-fns or dayjs

How to get date from js in correct format? Month and days get reversed

I am calling an ajax for getting some values for editing data.
As a part of my object, I am sending the date field.
My problem is that when I receive the date value in the controller, date format is wrong - my dates and months are reversed. And because of that I can't compare them where I need to.
But my months and days are reversed. For an example , instead of 3rd October, it returnes 10th of March.
How to fix this?
I am sending the date field from js in a object like this:
ExamsDataU = {
classId: classIdValue,
date: dateValue
};
And in my controller I tried:
DateTime dateToCheck = Convert.ToDateTime(dto.Date);
The first thing you should know is date parsing with Convert.ToDateTime() depends to the current culture used in server (you may check it using CultureInfo.CurrentCulture property). You can try one of these methods to parse JS date format properly inside controller action method:
1) Using DateTime.ParseExact()/DateTime.TryParseExact() with custom format
On this way it is necessary to specify date format before parsing date:
// specify custom format
string dateFormat = "dd-MM-yyyy";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture);
2) Using DateTime.ParseExact()/DateTime.TryParseExact() with ISO 8601 format
Use date: dateValue.toISOString(); to convert JS date into ISO 8601 format and then convert it:
// specify ISO format
string dateFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
This way is better than the former because no need to write additional date representation code in client-side, also you can adjust date representation to local time if necessary.
Notes:
a) For specified culture, you can try CultureInfo.GetCultureInfo():
var culture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.Name);
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, culture);
b) You can use if condition to check if the date string is valid when using DateTime.TryParseExact():
DateTime dateToCheck;
if (DateTime.TryParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateToCheck))
{
// do something
}
Try this
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
or
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);
console.log(newDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

No format support in Date object [duplicate]

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

Formatting the Date in JavaScript

Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?
You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:
http://blog.stevenlevithan.com/archives/date-time-format
Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.
If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.
For example, to get the current date in the format you want, you could do:
var myDate = new Date();
var dateStr = myDate.getFullYear +
'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
You may need to zero-pad the getDate() method if you require the two-digit format on the day.
I create a few useful js functions for date conversions and use those in my applications.
There's a very nice library to manage date in JS.
Try this.
You'll pretty much have to format it yourself, yeah.
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;
It's a bit long, but it'll work (:
add jquery ui plugin in your page.
function DateFormate(dateFormate, dateTime) {
return $.datepicker.formatDate(dateFormate, dateTime);
};
Just another option, which I wrote:
DP_DateExtensions Library
Not sure if it'll help, but I've found it useful in several projects.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.

Categories

Resources