mistake to convert date time in angular with moment library in angular - javascript

When I want to convert the Gregorian date to Persian date, it converts the value of the minute in the date conversion to error.
For example I want to convert this date time to Persian date:
2020-09-14T16:51:00+04:30 must convert to this 1399/06/24 16:51 but when convert date it show me this time 1399/06/24 00:06 it mistake to convert 16:51, show this: 00:06.
This is my code to convert date:
toPersianDate(date: any, format = 'YYYY/MM/DD HH:MM'): string {
let dateTime;
const MomentDate = moment(date, 'YYYY/MM/DD');
dateTime = MomentDate.locale('fa').format('jYYYY/jMM/jDD HH:jMM');
return dateTime;
}
What's the problem? How can I solve this problem?

the MM is used for month formatting, so it is trying to format the minutes into a month.
What you need to use is the small mm. Moreover, I don't this you need the j before the mm as the minutes are the same in Jalali time.
So what you actually need is this: MomentDate.locale('fa').format('jYYYY/jMM/jDD HH:mm');
You can read more about the formatting here.

Related

Format date and time from UTC with offset using date-fns

I have a UTC time with offset like below. I'm trying to format the UTC date time string using format function from date-fns library.
import { format } from "date-fns";
const utcDateTime = "2021-10-14T21:03:56.3256046+00:00";
const formattedDate = format(new Date(utcDateTime), "MM/dd/yyyy hh:mm");
What I'm expecting is 10/14/2021 21:03, a 24 hour time format but what I get is 10/14/2021 04:03, a converted date time for my timezone.
How to display the date and time exactly like with UTC time instead of converting the date time to local timezone?
I created a working example using CodeSandbox. Could anyone please help?
After spending a lot of time, I was able to achieve the desired result using the plain JavaScript Date object and its functions.
First, parsing the date time string and converting it to ISO string using toISOString() function.
Second, splitting the formatted date and time extracts from the ISO string.
Below is the code
const formatToUTCDateTime = (dateString) => {
const date = new Date(Date.parse(dateString));
const formattedDate = date.toISOString().split("T")[0].split("-");
const formattedTime = date.toISOString().split("T")[1].split(":");
return `${formattedDate[1]}/${formattedDate[2]}/${formattedDate[0]} ${formattedTime[0]}:${formattedTime[1]}`;
};
console.log("Result - ", formatToUTCDateTime("2021-10-14T20:03:56.3256046+00:00"));

How to convert string date to specific format?

I am trying to get date from string in specific format like:
const format = 'MM/dd/yyyy HH:mm';
const dt = "2021-03-11T22:00:00.000Z"; // expecting "03/11/2021 22:00"
console.log(moment(dt).format(format)); // but getting "03/Th/yyyy 23:00"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I tried js date, moment, luxon and I don't understand how to make this :(
I suspect that 000Z made problem but this is date I get.
The difference between Moment.js and Luxon is the case of the format keys. Please review the key/token tables.
Moment.js / String + Format
Luxon / Table of tokens
Note: Moment.js has been deprecated in favor of the team's newer library Luxon and other ECMA Script standards that are being introduced in ECMA-402. If you are considering using Moment.js now, just switch over to Luxon.
If you are using Luxon, you can call .toUTC() right before you format the date. Make sure your day of month (dd) and year (yyyy) format keys are lower-case.
const DateTime = luxon.DateTime;
const
format = 'MM/dd/yyyy HH:mm',
dt = "2021-03-11T22:00:00.000Z";
console.log(DateTime.fromISO(dt).toUTC().toFormat(format)); // 03/11/2021 22:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
If you are using Moment.js, you can call .utc() right before you format the date. Make sure your day of month (DD) and year (YYYY) format keys are upper-case.
const
format = 'MM/DD/YYYY HH:mm',
dt = "2021-03-11T22:00:00.000Z";
console.log(moment(dt).utc().format(format)); // 03/11/2021 22:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Your format string is wrong, it should be: 'MM/DD/YYYY HH:mm'.
Then, if your date comes with ':000Z', you should remove it with the substring() method.
Working code:
const format = 'MM/DD/YYYY HH:mm';
const dateString = "2021-03-11T22:00:00:000Z";
const date = dateString.substring(0, dateString.length - 5);
console.log(moment(date).format(format)); // prints 03/11/2021 22:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
You need to use YYYY instead of yyyy and DD instead of dd to get the expected result.
By the way, I suggest using another library than Moment, like dayjs for instance.

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>

How to get date & time using moment.js

I need to get the start date and end date in the below format using moment js
startDate = 20160427000000 and
endDate = 20160427235959
Here the start date appended with 000000 and end date appended with 235959
What is the right way to get this result in javascript
You want the format operator. Since it looks like your 0's and 2359's are hardcoded (I assume you're doing start and end of days), try:
startDate = moment().format('YMMDD000000');
endDate = moment().format('YMMDD235959');
EDIT: Or, as RobG pointed out, you can use:
startDate = moment().startOf('day').format("YMMDDHHmmss");
endDate = moment().endOf('day').format("YMMDDHHmmss");
(Which is much neater)
I'm totally confused, I don't know if you want to parse the format or output it. If you want to parse dates using moment.js in that format, then in time zone +05:30:
// Format YYYYMMDDHHmmss for 2016-04-26T00:00:00
var s = '20160426000000';
var x = moment(s, 'YYYYMMDDHHmmss');
// Show date in ISO 8601 extended format
console.log(x.format()); // 2016-04-26T00:00:00+05:30
To shift to the end of the day and output in YYYMMDDHHmmss format:
console.log(x.endOf('day').format('YYYYMMDDHHmmss')); // 20160426235959
In the format string:
YYYY is 4 digit year
MM is two digit month
DD is two digit day
HH is two digit hour in 24 hour format
mm is two digit minute
ss is two digit seconds
For Getting Format Like these in moment.js - (2020-12-15T13:00:00)
let a =2023-01-14T20:15:00-05:00
You can use moment(a).format("YYYY-MM-DDTHH:mm:ss")
Result: 2023-01-14T20:15:00

How to convert 2014-04-23T19:45:39 (UTC date) to AST date

I have a date like this:
2014-04-23T19:45:39 which is a UTC format.
I want to convert it to AST format or the localize time zone of the user. How to do it?
I suggest you use moment.js library and just add or subtract number of hours that AST time have comparing to UTC.
new_date = date.add('hours',4);
or
new_date = date.subtract('hours',4);
using timezone-js. you can easily convert the time from one timeZone to another. timezone.js
var date_object;
function localize(t){
date_object=new Date(t+" UTC");
document.write(date_object.toString());
}
localize("4/24/2014 4:52:48 PM")
document.write(date_object.toString().replace(/GMT.*/g,""));
Demo

Categories

Resources