Need to transform timestamp to mm/dd/yyyy format - javascript

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

Related

Angular 9 DatePipe: How to ignore timezone format

I am currently using angular 9 DateTime Pipe in order to format my dateTimes.
I am storing the dateTimes in database with DataTimeOffset.
When I am retrieving this dates from server are in this form: "2021-03-30T16:26:52.047+02:00"
I am using this code to apply the format to my dates:
const pipe = new DatePipe('en-Us);
const formatedDate = pipe.transform(date, 'dd.MMM.yyyy HH:mm:ss');
When I am doing this, the pipe is taking the browser time and format my date.
I know that this is the default option, if I am not sending the 3rd parameter to the transform function.
But I have a business need to show the dates as they are...but formatted in the format mentioned above,
My question is: How can I avoid the timeZone convert but still format the dateTime?
You may use var transformedDate = new Date(datepipe.transform(myDate, 'yyyy-MM-dd' + ' UTC'))
After many days of investigation, the only workaround was to use the library "Luxon".
https://moment.github.io/luxon/docs/manual/zones.html
With this library I can do something like this:
var keepOffset = DateTime.fromISO("2017-05-15T09:10:23-09:00", { setZone: true });
Which will keep the offset intact.

How do I reformat the date from openweather api using javascript? [duplicate]

This question already has answers here:
Format a date string in javascript
(7 answers)
Closed 2 years ago.
How do I format the date I receive from openweather api?
I currently get 2020-10-16 00:00:00 and I want 10-16-2020.
The reason I don't use moment is because I want future dates which come automatically with the 5 day forecast in the api.
You can use JavaScript's Date object.
You might save yourself time by searching a bit more before posting a question, the answer is probably already out there.
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Format JavaScript date as yyyy-mm-dd
You could try to:
Make a new date based on the date that comes from OpenWeather api
Convert it to a LocaleDateString using the 'en-US' locale. This will make the month appear before the date.
Then just split the Date String on the '/' and join in on a '-'. This will substitute the '/' with a '-'
const date = new Date("2020-10-16 00:00:00").toLocaleDateString('en-US');
const formatedDate = date.split('/').join('-');
console.log(formatedDate);
You can always use the built in Javascript Date object.
In your case you'd want to. do something like this -
const myDate = new Date('2020-10-16 00:00:00');
const date = myDate.getDate();
const month = myDate.getMonth() + 1;
const year = myDate.getFullYear();
console.log('MM-DD-YYYY', `${month}-${date}-${year}`);
If you want something more convinient and don't want to use moment you can also try some other popular date libraries. You can find some here - https://github.com/you-dont-need/You-Dont-Need-Momentjs

Why is moment converting this date incorrectly? [duplicate]

This question already has answers here:
moment.js - UTC gives wrong date
(3 answers)
Closed 3 years ago.
I have a GMT date and time format coming from my dynamodb which I'm trying to convert to EST format using momentjs.
2019-06-27 20:00:43.156257
As soon as I drop the date into moment, it's converting it to +4 hours (when its supposed to be -4).
2019-06-28T00:00:43.156Z
All I'm doing is this.
const dbdate = [value-from-db]
const momentdate = moment(dbdate);
My output looks like:
dbdate: 2019-06-27 20:00:43.156257
momentdate: 2019-06-28T00:00:43.156Z
There are two issues here:
1) Moment is performing timezone conversion using your local timezone - use moment.utc instead
2) Your date is not in a format that moment "officially" supports - although actually it's relaxed enough to parse your string. Ideally, it should be provided in proper ISO 8601 format to avoid any compatibility issues.
You could try something like:
const dbdate = '2019-06-27 20:00:43.156257'.split(' ');
const momentdate = moment.utc(dbdate[0] + 'T' + dbdate[1] + 'Z');
alert(momentdate);
Here's a fiddle.
Hope this helps!
You must use moment.utc() instead of moment():
const dbdate = '2019-06-27 20:00:43.156257';
const momentdate = moment(dbdate);
const utcmomentdate = moment.utc(dbdate);
console.log('local: \n', momentdate);
console.log('utc: \n', utcmomentdate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

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

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.

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

Categories

Resources